0
我有一個類爲ShopOrderRepository
和代碼以下,如何從另一個類創建一個類Singleton?
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));
}
}
而問題是什麼?你有什麼需要幫助的? –
我問的評論是打算利用'ShopOrderRepository'類單例。我所做的方式是否正確? – Arefe