我的应用程序需要轻量级和重量级的对象。是否有轻型和重型版本的对象的设计模式?
- 轻量级对象只包含ID字段,但不包含相关类的实例。
- 重量级对象将包含ID和这些类的实例。
下面是一个例子类(仅用于讨论的目的):
public class OrderItem
{
// FK to Order table
public int OrderID;
public Order Order;
// FK to Prodcut table
public int ProductID;
public Product Product;
// columns in OrderItem table
public int Quantity;
public decimal UnitCost;
// Loads an instance of the object without linking to objects it relates to.
// Order, Product will be NULL.
public static OrderItem LoadOrderItemLite()
{
var reader = // get from DB Query
var item = new OrderItem();
item.OrderID = reader.GetInt("OrderID");
item.ProductID = reader.GetInt("ProductID");
item.Quantity = reader.GetInt("Quantity");
item.UnitCost = reader.GetDecimal("UnitCost");
return item;
}
// Loads an instance of the objecting and links to all other objects.
// Order, Product objects will exist.
public static OrderItem LoadOrderItemFULL()
{
var item = LoadOrderItemLite();
item.Order = Order.LoadFULL(item.OrderID);
item.Product = Product.LoadFULL(item.ProductID);
return item;
}
}
是否有一个很好的设计模式遵循做到这一点?
我可以看到它是如何被编码到一个类中的(正如我上面的例子),但它并不明显以何种方式使用实例。我需要在我的代码中进行NULL检查。
编辑: 此对象模型用于客户端服务器应用程序的客户端。在我使用轻量级对象的情况下,我不想延迟加载,因为这会浪费时间和内存(我已经将对象放在客户端的其他内存中)
我并不总是想要加载完整的对象。有时,我已经有了它的一个实例,所以我不需要从DB重新加载。 – TheSean 2012-04-25 19:55:37
@TheSean无所谓。这正是该模式的实用性。如果你需要使用它们,那么你加载它们,否则不。现在,如果你正在谈论不暴露重型版本的属性,但也可以通过使用(即两个接口:较轻的和较重的接口)来解决。 – 2012-04-25 19:58:14
举个例子,假设我有1000个订单,每个订单都是同一个产品。使用延迟加载Product对象的建议,我将加载同一对象的1,000个实例。这就是我的意思是浪费记忆。 – TheSean 2012-04-25 20:18:29