Complex objects design: so as to not have to retrieve the entire object graph
Not sure what the best title would be for this question, or even if I am being clear, but here it is:
What is the best way to setup complex objects so as to not have to retrieve the entire object graph when the parent object is first being accessed?开发者_开发百科
For example: Order
has a customer
order lines (many)
product
- price
pricing details (discounts, etc)
order status
status
fulfilment date
Would you create the Order with all its dependent objects as properties or would you provide accessor method for the dependent objects?
example:
Option 1:
class Order
public property Customer
public property List of Order Lines
Option 2:
class Order
- public GetCustomer():Customer
- public GetOrderLines():List of order lines
The way I see it each has its own advantages and disadvantages:
Option 1: Class diagrams show the relationship between different objects. The disadvantage is that when you are getting the Order object, you need to get the entire object graph (which could get expensive and in many cases might be unnecessary).
Option 2: Because each object is retrieved through a Get call, you can defer the actual retrieval to when the object is needed. Disadvantage, at least in Visual Studio class diagrams, you can no longer get nice relationships between the different objects.
Are there any other design patterns that can accomplish what I am trying more efficiently?
Would you consider using an ORM such as Entity Framework or NHibernate? That way, you'll get Lazy Loading support without having to go through a lot of trouble implementing it yourself.
The choices of Property vs getter method and lazy loading vs full object graph are orthogonal, you can pretty much have any combination of them.
I'd probably choose a Property here since it's more idiomatic to C#. As for deferring the object retrieval, it depends on your context - like anon wrote, when drawing from database data lazy loading can be appreciable.
精彩评论