如何从另一个类创建一个类Singleton?

时间:2017-02-04 15:02:09

标签: java design-patterns singleton

我有一个ShopOrderRepository的课程,代码正在关注,

public class ShopOrderRepository {

    private IModelFactory modelFactory;

    public ShopOrderRepository(IModelFactory modelFactory)
    {
        this.modelFactory = modelFactory;
    }

    public ShopOrder loadShopOrder(String shopOrderId)
    {
        ShopOrder order = modelFactory.getShopOrder(); 
        order.setId(shopOrderId);
        List<OrderLine> orderLines = new ArrayList<OrderLine>();
        orderLines.add(getOrderLine("1","Keyboard",1));
        order.setOrderLines(orderLines);
        return order;
    }

    private OrderLine getOrderLine(String productId, String name, int quantity) 
    {
        OrderLine orderLine = modelFactory.getOrderLine();
        Product product = modelFactory.getProduct();
        product.setId(productId);
        product.setName(name);
        orderLine.setProduct(product);
        orderLine.setQuantity(quantity);
        return orderLine;
    }

    public void saveShopOrder(ShopOrder shopOrder)
    {
        System.out.println("Hurray, you saved the shopOrder: "+shopOrder);
    }

}

现在,我有另一个类BackendContainer实现了一个接口,并在下面提供,

public class BackendContainer implements IModelFactory {

    public BackendController getBackendController() 
    {
        return new BackendController(getShopOrderRepository());
    }

    // TODO: should be a singleton
    public ShopOrderRepository getShopOrderRepository() 
    {
        return new ShopOrderRepository(this);
    }
}

现在,getShopOrderRepository方法有一个注释顶部,它告诉我们将类ShopOrderRepository设为Singleton。所以,我写如下,

public class BackendContainer implements IModelFactory {

  private ShopOrderRepository  shopOrderRepository; 

        public BackendController getBackendController() 
        {
            return new BackendController(getShopOrderRepository());
        }

        // TODO: should be a singleton
        public static ShopOrderRepository getShopOrderRepository() 
        {
            // return new ShopOrderRepository(this);
             return shopOrderRepository !=  null ? shopOrderRepository: (shopOrderRepository =  new ShopOrderRepository(this));
        }
    }

1 个答案:

答案 0 :(得分:-1)

这是我的答案,

public class BackendContainer implements IModelFactory {

    private ShopOrderRepository shopOrderRepository;

    public BackendController getBackendController()
    {
        return new BackendController(null);
    }

    /**
     * Instantiates a singleton ShopOrderRepository instance per BackendContainer instance
     * @return ShopOrderRepository
     */
    public ShopOrderRepository getShopOrderRepository() {

        if(shopOrderRepository == null) {
            synchronized(ShopOrderRepository.class) {
                if (shopOrderRepository == null) {
                    shopOrderRepository = new ShopOrderRepository(this);
                }
            }
        }

        return shopOrderRepository;
    }
}