前面讲到的简单工厂如下面这段代码,后续需要拓展功能时,需要在简单工厂里面添加 case ,这依旧违反了开放-封闭中的对修改关闭的原则。
// 工厂生成对象类
public class OperationFactory
{
public static OperationClass GetOperation(string operationType)
{
OperationClass opera = null;
switch (operationType)
{
case "+":
opera = new AddOperation();
break;
case "-":
opera = new SubOperation();
break;
case "*":
opera = new MulOperation();
break;
case "/":
opera = new DivOperation();
break;
case "sqrt":
opera = new SqrtOperation();
break;
case "squa":
opera = new SquareOperation();
break;
default:
break;
}
return opera;
}
}
一、将一个雷锋的简单工厂修改成工厂模式
1. 简单工厂实现代码
public class LeiFeng
{
public void Sweep()
{
Console.WriteLine("扫地");
}
public void Wash()
{
Console.WriteLine("洗衣");
}
public void BuyRice()
{
Console.WriteLine("买米");
}
}
public class Undergraduate : LeiFeng { }
public class Volunteer : LeiFeng { }
public class SimpleFactory
{
public static LeiFeng CreateLeiFeng(string type)
{
LeiFeng result = null;
switch (type)
{
case "big student":
result = new Undergraduate();
break;
case "volunteer":
result = new Volunteer();
break;
default:
break;
}
return result;
}
}
LeiFeng studentA = SimpleFactory.CreateLeiFeng("big student");
studentA.Sweep();
LeiFeng studentB = SimpleFactory.CreateLeiFeng("big student");
studentB.Wash();
LeiFeng studentC = SimpleFactory.CreateLeiFeng("big student");
studentC.BuyRice();
2. 工厂模式实现代码
结构是这样的
sequenceDiagram
Creator->>Product: 创造生产者
ConcreteCreator->>ConcreteProduct: 工厂创造生产者
ConcreteCreator->>Creator: 继承
ConcreteProduct->>Product: 继承
public interface IFactory
{
LeiFeng CreateLeiFeng();
}
public class UndergraduateFactory : IFactory
{
public LeiFeng CreateLeiFeng()
{
return new Undergraduate();
}
}
public class VolunteerFactory : IFactory
{
public LeiFeng CreateLeiFeng()
{
return new Volunteer();
}
}
IFactory factory = new UndergraduateFactory();
LeiFeng lf = factory.CreateLeiFeng();
lf.Sweep();
lf.Wash();
lf.BuyRice();
后面要改只需要改第一行:IFactory factory = new UndergraduateFactory();
3. 你可能会说,那工厂其实没什么作用,直接一句不就可以了:
LeiFeng lf = new Undergraduate();
结构如下
graph LR
ConcreteProduct--继承-->Product
这不够规范,而且工厂模式可以结合单例模式。