《大话设计模式》读书笔记6 工厂方法模式
工厂方法(Factory Method)模式:定义一个用于创建对象的接口,让子类决定实例化哪一个类,工厂方法使一个类的实例化延迟到其子类。
工厂方法模式结构图:
工厂方法模式实现代码:
class Leifeng
{
public void Sweep()
{
Console.WriteLine("扫地");
}
public void Wash()
{
Console.WriteLine("洗衣");
}
public void BuyRice()
{
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();
}
}
IFactory factory=new UndergraduateFactory();
Leifeng student=factory.CreateLeiFeng();
student.BuyRice();
student.Sweep();
student.Wash();