对象的轻型和重型版本是否有设计模式?

The*_*ean 6 .net c# design-patterns

在我的应用程序中,我需要轻量级和重量级的对象版本.

  • 轻量级对象仅包含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;
    }
}
Run Code Online (Sandbox Code Playgroud)

是否有良好的设计模式可以实现这一目标?

我可以看到如何将它编码到一个类中(如上面的例子),但是使用实例的方式并不明显.我需要在整个代码中进行NULL检查.

编辑: 此对象模型正在客户端 - 服务器应用程序的客户端上使用.在我使用轻量级对象的情况下,我不想要延迟加载,因为它会浪费时间和内存(我已经在客户端的内存中有对象)

小智 2

您是否考虑过使用像 NHibernate 这样的 ORM 工具来访问数据库?如果您使用 NHibernate 之类的东西,您将通过延迟加载来获得此行为。

大多数 ORM 工具完全符合您在延迟加载中寻找的功能 - 它们首先获取对象标识符,然后在访问方法时发出后续查询来加载相关对象。