工厂方法模式
是简单工厂模式的进一步抽象,封装了对象创建的过程,让子类决定是实例化哪个对象。把简单工厂模式的内部判断转移到客户端代码,如果更改功能,需要更改客户端代码,而不用动工厂类。
电脑的案例
- PC类
class PC
{
public void KeyBoard()
{
Console.WriteLine("KeyBoard");
}
public void Mouse()
{
Console.WriteLine("Mouse");
}
}
class HpPC : PC { }
class DellPC: PC { }
- PC工厂类
interface IPCFactory
{
PC CreatePC();
}
class HPFactory : IPCFactory
{
public PC CreatePC()
{
return new HpPC();
}
}
class DellFactory : IPCFactory
{
public PC CreatePC()
{
return new DellPC();
}
}
- 制造(需要换厂商,只需更改factory的实例化)
static void Main(string[] args)
{
IPCFactory factory = new HPFactory();
PC myPC = factory.CreatePC();
myPC.KeyBoard();
myPC.Mouse();
}