工厂方法模式
下面用一个例子解释:
2个接口:电视及洗衣机
1个抽象工厂
2个具体电视机类 ,2个具体洗衣机类 ,2个具体工厂类
一个客户端
//TV接口
namespace FactoryMethodModel { interface ITV { string play(); }
}
class HaierTV:ITV { public string play() { string str = "Haier电视正在播放...."; return str; } } class TCLTV : ITV { public string play() { string str = "TCL电视正在播放...."; return str; } }
namespace FactoryMethodModel { interface IWashing { string washing(); } class HaierWashingMachine:IWashing { public string washing() { string str = "Haier洗衣机正在洗涤...."; return str; } } class TCLWashingMachine:IWashing { public string washing() { string str = "TCL 洗衣机洗涤中...."; return str; } } }
namespace FactoryMethodModel { abstract class AbstractFactory { public abstract ITV productTV(); public abstract IWashing productWashing(); } class HaierFactory:AbstractFactory { public override ITV productTV() { return new TCLTV(); } public override IWashing productWashing() { return new HaierWashingMachine(); } } class TCLFactory:AbstractFactory { public override ITV productTV() { return new TCLTV(); } public override IWashing productWashing() { return new TCLWashingMachine(); } } }
/*工厂方法模式*/ namespace FactoryMethodModel { class Client { static void Main(string[] args) { //TotalFactory t = new TotalFactory(); //监护所有的工厂 //t.SetFactory(new TCLFactory()); TotalFactory t = new TotalFactory(new TCLFactory()); Console.WriteLine(t.productTV().play()); Console.WriteLine(t.productWashingMachine().washing()); Console.ReadKey(); } } }
//为了方便管理可以创建一个总工厂用来管理所有工厂 namespace FactoryMethodModel { class TotalFactory { AbstractFactory abstractFactory; ITV tv; IWashing wash; Type factoryType; public TotalFactory() { } public TotalFactory(AbstractFactory factory) { SetFactory(factory); } public void SetFactory(AbstractFactory factory) { factoryType = factory.GetType(); GetFactoryByType(); abstractFactory = GetFactoryByType(); tv = abstractFactory.productTV(); wash = abstractFactory.productWashing(); } public AbstractFactory GetFactoryByType() { if (factoryType == typeof(TCLFactory)) { return new TCLFactory(); } else if (factoryType == typeof(HaierFactory)) { return new HaierFactory(); } else { return null; } } public ITV productTV() { return tv; } public IWashing productWashingMachine() { return wash; } } }