简体   繁体   English

向抽象工厂添加属性

[英]Adding Properties to Abstract Factory

I am relatively new to design patterns and am playing around with the GangOfFour Abstract Factory pattern in a project I am working on. 我对设计模式比较陌生,并且在我正在研究的项目中使用GangOfFour Abstract Factory模式。 I wanted to know the best way to introduce a property of type string called FileName which is needed for all of the Abstract Products produced by a Concrete Factory. 我想知道引入名为FileName的字符串类型的属性的最佳方法,这是混凝土工厂生产的所有抽象产品所必需的。 Would I 我可以吗

Add it to the Abstract Factory interface so that it has to be implemented down the tree and passed into the constructor of the returned Product. 将其添加到Abstract Factory接口,以便必须在树下实现它,并将其传递到返回的Product的构造函数中。 even though that interface is only concerned with creating factories? 即使该接口仅与创建工厂有关?

I will use a section of the GoF .Net Optomised code to use an example as its simple any anybody else learning these patterns will be familiar with it and may provide a good reference point in the future. 我将使用GoF .Net Optomized代码的一部分来使用示例,因为它简单易懂,任何其他学习这些模式的人都将熟悉它,并且将来可能会提供一个很好的参考点。

/// <summary>
/// The 'AbstractFactory' interface. 
/// </summary>
interface IContinentFactory
{
    // Define property in here??
    IHerbivore CreateHerbivore();
    ICarnivore CreateCarnivore();
}

/// <summary>
/// The 'ConcreteFactory1' class.
/// </summary>
class AfricaFactory : IContinentFactory
{
    // Implement property in here??
    public IHerbivore CreateHerbivore()
    {
        return new Wildebeest(PassInPropertyHere??);
    }

    public ICarnivore CreateCarnivore(PassInPropertyHere??)
    {
        return new Lion();
    }
}

I think it depends on the nature of objects that are created by factory and factories themselves. 我认为这取决于工厂和工厂本身创建的对象的性质。 If it cannot be created without some information (like FileName in this case) you have two choices: either your factories know that data or you need to supply it to factories (and one the options here is to pass that data during method call). 如果无法在没有某些信息的情况下创建数据(例如本例中的FileName),则有两种选择:工厂知道该数据或需要将其提供给工厂(这里的一种选择是在方法调用期间传递该数据)。 Otherwise if this information is optional from creation point of view you should not clutter factories with this and put this burden on the calling code (for example, FileName property of the created object can be set to necessary value right after the object is returned from factory). 否则,如果从创建的角度来看此信息是可选的,则您不应以此来使工厂杂乱无章,并将此负担加在调用代码上(例如,可以将对象从工厂返回后立即将所创建对象的FileName属性设置为必要的值) )。

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

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