抽象工厂的具体实例:
用Factory Method模式设计一个电视机工厂:
要求为每种品牌的电视机提供一个子工厂,如:海尔工厂专门负责生产海尔电视机,海信工厂专门负责生产海信电视机,如果需要生产TCL电视机或创维电视机,只需要对应增加一个新的TCL工厂或创维工厂即可,原有的工厂无须做任何修改,使得整个系统具有更加的灵活性和可扩展性。
类图:
说明:此类图由Visual studio 2012根据源码自动生成,Program可视为调用工厂的Client。
由类图可见我单独为电视产品申明了一个顶层的抽象类,之后是海尔和海信各自的产品抽象类,然后具体的产品类由各自的产商自己实现。同时产品的工厂类也是由一个顶层的抽象工厂类,下面派生了两个具体的海尔工厂类和海信工厂类。
Factory类实现源码:using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace AbstractTVFactory { //抽象的TV abstract class AbsTVFactory { //private String Brand; abstract public AbsTVProduct BuildProduct(); } //具体的电视品牌的抽象工厂 class HairFactory : AbsTVFactory { //public void getBrand() //{ // //throw new NotImplementedException(); // Console.WriteLine("Hair Brand"); //} public override AbsTVProduct BuildProduct() { //throw new NotImplementedException(); return new HairTV1(); } } class HisenseFactory : AbsTVFactory { public override AbsTVProduct BuildProduct() { return new HisenseTV1(); } } abstract class AbsTVProduct { abstract public void TVProduct(); } //下面是抽象的产品TV类 abstract class AbsHairTVProduct:AbsTVProduct //海尔的产品抽象类 { abstract override public void TVProduct(); } abstract class AbsHisenseTVProduct : AbsTVProduct //海信的产品抽象类 { abstract override public void TVProduct(); } //具体的TV类 class HairTV1 : AbsHairTVProduct //海尔的TV产品1 { public override void TVProduct() { Console.WriteLine("This is Hair TV Product! " + this.GetType().ToString()); } } class HairTV2 : AbsHairTVProduct //海尔的TV产品2 { public override void TVProduct() { Console.WriteLine("This is Hair TV Product! "+this.GetType().ToString()); } } class HisenseTV1 : AbsHisenseTVProduct { public override void TVProduct() { //throw new NotImplementedException(); Console.WriteLine("This is Hisense TV Product! " + this.GetType().ToString()); } } class HisenseTV2 : AbsHisenseTVProduct { public override void TVProduct() { //throw new NotImplementedException(); Console.WriteLine("This is Hisense TV Product! " + this.GetType().ToString()); } } }客户端运行源码:
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace AbstractTVFactory { class Program { static void Main(string[] args) { AbsTVFactory HairTVFactory = new HairFactory(); AbsHairTVProduct HairTV_1=new HairTV1(); //海尔TV种类1 HairTV_1=(AbsHairTVProduct)HairTVFactory.BuildProduct(); HairTV_1.TVProduct(); AbsHairTVProduct HairTV_2 = new HairTV2(); //海尔的TV种类2 HairTV_2 = (AbsHairTVProduct)HairTVFactory.BuildProduct(); HairTV_2.TVProduct(); //海信的TV AbsTVFactory HisenseTVFactory = new HisenseFactory(); AbsHisenseTVProduct HisenseTV_1 = new HisenseTV1(); //海信的TV种类1 HisenseTV_1 = (AbsHisenseTVProduct)HisenseTVFactory.BuildProduct(); HisenseTV_1.TVProduct(); AbsHisenseTVProduct HisenseTV_2 = new HisenseTV2(); //海信的TV种类2 HisenseTV_2 = (AbsHisenseTVProduct)HisenseTVFactory.BuildProduct(); HisenseTV_2.TVProduct(); Console.ReadKey(); } } }
运行截图:
直观的关系图: