简体   繁体   English

如何在工厂方法设计模式中添加不同的参数集以实现正确的设计

[英]How to add different set of parameters to factory method design pattern to achieve proper design

I have a scenario where two different classes have many properties and one different property. 我有一个场景,其中两个不同的类具有许多属性,而一个具有不同的属性。 How do I use factory design pattern or should I not use it? 如何使用工厂设计模式,或者不应该使用它? Internal private methods of these sub classes make use of these properties. 这些子类的内部私有方法使用这些属性。

public class RunsValidator  
{  
     //Few common properties  
     public int DataSegmentID { get; set; }  
     public int AttributeOffset { get; set; }  
}

public class ProductAttributeRunValidator : RunsValidator  
{

    public ProductAttributeRunValidator(string productNames)
    {
       this.ProdNames = productNames;
    }
}

public class CategoryAttributeRunValidator : RunsValidator  
{  

     public CategoryAttributeRunValidator(int orgIDs) : base()  
          {  
            this.totalOrgIDs = orgIDs;  
          }  

}  

//Factory implementation //工厂实现

public class RunAttributeFactory  
{     

    public static RunsValidator GetRunValidator(string type, string productNames, int orgIds)  
     {  
      RunsValidator runValidator = null;  
      if(type == "Product")  
      {   
           runValidator = new ProductAttributeRunValidator(productNames);  
      }  
      else if (type == "Category")  
      {  
           runValidator = new CategoryAttributeRunValidator(orgIds);  
      }  
      else  
      {  
          runValidator = null;  
      }  
      return runValidator;  
    }  
}

In the client code, I have access to variables that should be sent as parameters (productNames, orgIds and type) to the Factory method. 在客户端代码中,我可以访问应作为参数(productName,orgId和type)发送到Factory方法的变量。 I would like to access the returned runValidator in many places in the client code as it needs to be set only once based on the type. 我想在客户端代码的许多地方访问返回的runValidator,因为仅需根据类型将其设置一次。

Which is the best way to achieve this? 哪个是实现此目标的最佳方法?

Considering that the client will have to know the type of the output to know what parameters to pass in, and that you have no re-usable code between the two types, I see no value from a "generic" factory pattern here. 考虑到客户端将必须知道输出的类型才能知道要传入的参数,并且您在这两种类型之间没有可重用的代码,因此我在这里看不到“通用”工厂模式的值。 I would either have two factories (if you even need a factory for either type), or let the client call the type constructor directly. 我要么有两个工厂(如果您甚至需要为一个类型创建工厂),要么让客户端直接调用类型构造函数。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM