工厂模式,将满足开放/关闭原则? [英] A Factory Pattern that will satisfy the Open/Closed Principle?
问题描述
我有以下具体动物
产品:狗
和猫
。
I have the following concrete Animal
products: Dog
and Cat
.
我使用的参数的工厂方法创建表示产品。根据传递给工厂方法的 AnimalInfo
参数,具体的产品将被创建。该映射逻辑放置在工厂方法
I am using a parameterized Factory method to create said products. Depending on the AnimalInfo
parameter that is passed to the Factory method, a concrete product will be created. The mapping logic is placed in the Factory method.
下面是我的代码:
public abstract class AnimalInfo
{
public abstract String Sound { get; }
}
public class DogInfo : AnimalInfo
{
public override string Sound
{
get { return "Bark"; }
}
}
public class CatInfo : AnimalInfo
{
public override string Sound
{
get { return "Meow"; }
}
}
public abstract class Animal
{
public abstract void Talk();
}
public class Dog : Animal
{
private readonly DogInfo _info;
public Dog(DogInfo aInfo)
{
_info = aInfo;
}
public override void Talk()
{
Console.WriteLine(_info.Sound);
}
}
public class Cat : Animal
{
private readonly CatInfo _info;
public Cat(CatInfo aInfo)
{
_info = aInfo;
}
public override void Talk()
{
Console.WriteLine(_info.Sound);
}
}
下面是我的工厂方法与逻辑:
Here's my Factory method with its logic:
public static class AnimalFactory
{
public static Animal CreateAnimal(AnimalInfo aInfo)
{
if (aInfo is DogInfo)
return new Dog(aInfo as DogInfo);
if (aInfo is CatInfo)
return new Cat(aInfo as CatInfo);
return null;
}
}
我看到这里的问题是,工厂方法本身违反了打开/以这样的方式,如果我添加一个新的动物闭原则,我将需要修改的工厂方法,以反映新的映射。
The problem I'm seeing here is that the Factory method itself violates the Open/Closed principle in such a way that if I add a new Animal, I will need to modify the Factory method to reflect the new mapping.
有没有一种方法,使创作更动态通过反射?更重要的是,有没有在我的设计的反模式?
Is there a way to make the creation more "dynamic" via reflection? More importantly, is there any anti-pattern in my design?
推荐答案
最简单的办法就是让 AnimalInfo
本身工厂:
The easy way out is to make AnimalInfo
itself the factory:
public abstract class AnimalInfo<T> where T: Animal
{
public abstract String Sound { get; }
public abstract T CreateAnimal();
}
有关DogInfo
实施
Implementation for DogInfo:
public class DogInfo : AnimalInfo<Dog>
{
public override string Sound
{
get { return "Bark"; }
}
public override Dog CreateAnimal()
{
return new Dog(this);
}
}
您可以保留当前的静态工厂,如果你想
You could keep your current static Factory if you wanted to:
public static class AnimalFactory
{
public static Animal CreateAnimal(AnimalInfo aInfo)
{
return aInfo.CreateAnimal();
}
}
不完全是严格adherance到工厂模式,国际海事组织,但不再侵犯了您的开/关的原则。
Not exactly strict adherance to the Factory pattern, IMO, but no longer violates your open/close principle.
这篇关于工厂模式,将满足开放/关闭原则?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!