0

I have a question about IOC, factories, and the Open/Closed principle.

consider, if you will, the following factory

public function PODocument( _type as string) as IPODocument

      dim d as new PODocument
      if _type = "service" then 
         d.header = new ServicePOHeader()
         d.details = new ServicePOLineItems()
      else if _type = "merchandise" then 
         d.header = new MerchandisePOHeader()
         d.details = new MerchandisePOLineItems()
      end if 

    return d

end function 

This is working for me and I can nicely have a webpage show information about heterogeneous collections.

My challenge is that today someone told me sometimes a certain customer will order a service and merchandise together. Come on, who among us could have seen that coming?

So I write a new set of providers that handle the added complexity, changed the factory to include a case for the new type, I'm back off and running.

However, I have violated the open/closed principle by changing the factory, which was released to production. Is there a way to set this up so that I am not constantly changing the factory?

thanks in advance.

4

1 回答 1

1

是的。对于您的案例,最简单的示例是为每个 定义一个工厂类_type,并将它们命名为ServiceFactoryMerchandiseFactory等,或者<PODocumentType("Service")>在它们上放置一个 etc。

然后只需找到所有工厂(例如,使用反射),将它们放入 aDictionary(Of String, IPODocumentFactory)并根据 key 选择正确的工厂。

在更复杂的情况下,IPODocumentFactory接口可能包括CanCreate()除了Create(). 然后您可以根据其对当前情况的看法在列表中选择一个工厂。

请注意,发现和列表解析支持通常由 DI 框架(如 Unity 或 Autofac)开箱即用地提供。

于 2013-05-06T03:19:53.760 回答