samedi 4 février 2017

How to make a class Singleton from the another class?

I have a class for ShopOrderRepository and the code is following,

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);
    }

}

Now, I have another class namely BackendContainer implements an interface and provided below,

public class BackendContainer implements IModelFactory {

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

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

Now, there is a comment top of the getShopOrderRepository method and its telling to make the class ShopOrderRepository as Singleton. So, I write as following,

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));
        }
    }

Aucun commentaire:

Enregistrer un commentaire