工厂模式目的只是用于创建对象,但简单的工厂模式始终对子类有存在依赖,你每建立一个子类,则必须对Factory进行修改。
class Factory
{
public Farther Create(int n)
{
swith(n)
{
case 0:
return new Child1();
.........
}
}
}
而策略模式所关注是其行为,当你调用不同的子类,则会实现不同的效果。Strategy只是承担“中介者”的角色,strategy的行为将委托于子类来实现。但Strategy没有违反DIP原则,对子类不存在依赖,只是开发时需要多建一个类。
class Strategy
{
private Father class;
public void SetData(Father child)
{
class=child;
}
public void Method()
{
//利用不同child实现不同效果
...........
}
}
class Father{.........}
class Child:Father{........}