工厂(Factory)模式定义:定义一个用于创建对象的接口,让子类决定实例化哪一个类,工厂方法使一个类的实例化延迟到子类。
工厂方法把简单工厂的内部逻辑判断移到了客户端代码来进行,想要加新功能,本来是改工厂类,现在是修改客户端。
代码例子背景:大学生学习雷锋做好事,课余时间去孤寡老人家里扫地、洗衣服做家务,但是不需要让老人知道学做雷锋的是大学生还是社区志愿者,因为雷锋做好事不留名。
雷锋类:包含具体要实现的功能
class LeiFeng
{
public void Sweep()
{
Console.WriteLine("扫地");
}
public void Wash()
{
Console.WriteLine("洗衣");
}
public void BuyRice()
{
Console.WriteLine("买米");
}
}
简单工厂模式:使用逻辑判断选择实例化相应的类,添加新类要修改原码,违反开闭原则。
class SimpleFactory
{
public static LeiFeng CreateLeiFeng(string type)
{
LeiFeng result = null;
switch (type)
{
case "学雷锋的大学生":
result = new Undergraduate();
break;
case "社区志愿者":
result = new Volunteer();
break;
}
return result;
}
}
客户端:
class Program
{
static void Main(string[] args)
{
LeiFeng studentA = SimpleFactory.CreateLeiFeng("学雷锋的大学生");
studentA.BuyRice();
LeiFeng studentB = SimpleFactory.CreateLeiFeng("学雷锋的大学生");
studentB.Sweep();
LeiFeng studentC = SimpleFactory.CreateLeiFeng("学雷锋的大学生");
studentC.Wash();
}
}
工厂模式:
- 定义一个接口
interface IFactory
{
LeiFeng CreateLeiFeng();
}
- 实例化子类分别实现接口
class Undergraduate:LeiFeng
{
}
class Volunteer :LeiFeng
{
}
//学雷锋的大学生工厂
class UndergraduateFactory : IFactory
{
public LeiFeng CreateLeiFeng()
{
return new Undergraduate();
}
}
//社区志愿者工厂
class VolunteerFactory : IFactory
{
public LeiFeng CreateLeiFeng()
{
return new Volunteer();
}
}
客户端:
class Program
{
static void Main(string[] args)
{
IFactory factory = new UndergraduateFactory();
LeiFeng student = factory.CreateLeiFeng();
student.BuyRice();
student.Sweep();
student.Wash();
}
}