工厂只创建正确的类型
所以这里是一个Factory
只返回正确类型的例子:
public class BirdFactory
{
public static IBird CreateBird(string birdType)
{
switch (birdType)
{
case "Eagle":
return new Eagle();
case "Penguin":
return new Penguin();
}
}
}
像这样使用:
IBird bird = BirdFactory.CreateBird("eagle");
bird.FlyToLocation(new Location("London"));
考虑创建正确的类型和设置状态
以下是用于设置状态和类型的工厂示例:
public class BirdFactory
{
public static IBird CreateBird(string birdType, Location locationToFlyTo)
{
switch (birdType)
{
case "Eagle":
return new Eagle(locationToFlyTo);
case "Penguin":
return new Penguin(locationToFlyTo);
}
}
}
像这样使用:
IBird bird = BirdFactory.CreateBird("eagle", new Location("London"));
bird.FlyToLocation();
问题
第二种做法的可接受程度如何?哪个更易维护?