为类版本控制创建多个类或使用Switch语句的最佳做法是什么

时间:2012-07-27 05:13:40

标签: oop design-patterns

在我的项目中,我必须维护类的版本。所以我可以采用两种方法

 1) Edit Same Class with Version and Use Switch Case for maintain older version

    Pro : 
    1) We only have to create one single class  
    2) If you want to used old version class attribute which are now not supported in
       current version of class so you just provide them Default Values.

    Cons:
    1) There may be possibility that some attribute are not used now but they still
       present in Class for supporting older version
    2) It also break Open Closed Principle

下一步方法:

 2) Create new classes for each version and maintain them by using any design pattern 
   so for example I have Base Class = BaseClass and It have multiple Derived classes 
   like DerivedClass1,DerevivedClass2. Each class have different version.

   Pro:
   1) If now we want to use old version class so we not have to worry about its 
   attribute behavior  because we will fetch DerivedClass1 for Version 1 ,    
   DerivedClass2 for Version 2
   2) We will put all common property in Base class so Derived class will only have 
    extended property.
   3) We also follow Open Closed Principle

   Cons: 
   1) We need to create new classes for all new versions.

所以,我想知道您对此的看法,如果您需要更多说明,请与我们联系。

1 个答案:

答案 0 :(得分:0)

对您的问题的回答通常取决于将如何使用版本控制类:

  • 如果它们是等数据的容器,请查看适配器间接层模式, 例子。特别是如何同时处理不同版本的Web服务或数据库。

  • 如果它们是不同版本算法的容器,那么抽象工厂模式可能会与您同在!

对我来说,你的第一个建议是把所有鸡蛋放在一个班级,并用属性配置它,听起来像是噩梦,不值得花时间。