我有一个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));
}
}
答案 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;
}
}