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. 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. 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. 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.
/// <summary>
/// The 'AbstractFactory' interface.
/// </summary>
interface IContinentFactory
{
// Define property in here??
IHerbivore CreateHerbivore();
ICarnivore Cr开发者_开发问答eateCarnivore();
}
/// <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). 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).
精彩评论