简单工厂模式的最大优点在于工厂类包含了必要的逻辑的推断,根据客户端的选择条件动态实例化相关的类,对于客户端来说,去除了与具体产品的依赖。
但因为修改了工厂类,违背了开放封闭原则。
工厂方法模式,定义一个创建工厂的接口,让子类决定实例化那一个类。工厂方法是工厂类的实例化延迟到其子类。
但工厂方法模式也有一定的问题,客户端需要决定实例化哪一个工厂来实现运算类,其选择问题还是存在的,也就是工厂方法模式把简单工厂模式的内部逻辑判断
移动到了客户端代码来进行。·
class Program
{
class LeiFeng
{
public void Sweep()
{
Console.WriteLine("扫地");
}
}
class Undergraduate : LeiFeng
{
}
class Volunteer : LeiFeng
{
}
interface Ifactory
{
LeiFeng CreateLeiFeng();
}
class UndergraduateFactory : Ifactory
{
public LeiFeng CreateLeiFeng()
{
return new Undergraduate();
}
}
class VolunteerFactory : Ifactory
{
public LeiFeng CreateLeiFeng()
{
return new Volunteer();
}
}
static void Main(string[] args)
{
Console.WriteLine("begin");
Ifactory factory = new UndergraduateFactory();
LeiFeng student1 = factory.CreateLeiFeng();
student1.Sweep();
Ifactory factory1 = new VolunteerFactory();
LeiFeng vol = factory.CreateLeiFeng();
student1.Sweep();
}
}