创建型设计模式,围绕一个超级工厂创建其他工厂,是其他工厂的工厂,基于工厂模式,提供一个接口去创建其他工厂。
实例应用:购买商品,商品可以分为不同品牌的商品,而每个品牌下又不止一个或一种商品。
优点:解决接口选择问题,保证客户端使用同一个产品族中的对象
缺点:产品族扩展性低
代码实现:
1、创建小米品牌、晨光品牌接口
public interface IMIBrand
{
void PrintName();
}
public interface IMorningLight
{
void PrintIn();
}
2、创建小米旗下商品、晨光旗下商品
小米:
public class MIPhone : IMIBrand
{
public void PrintName()
{
Console.WriteLine("小米手机");
}
}
public class USBStorage : IMIBrand
{
public void PrintName()
{
Console.WriteLine("U盘");
}
}
晨光:
public class NoteBook : IMorningLight
{
public void PrintIn()
{
Console.WriteLine("笔记本");
}
}
public class Pen : IMorningLight
{
public void PrintIn()
{
Console.WriteLine("钢笔");
}
}
3、创建抽象类
public abstract class AbstractFactory
{
public abstract IMIBrand GetMIBrand(string type);
public abstract IMorningLight GetMorningLight(string type);
}
4、创建小米工厂类、晨光工厂类,继承抽象类,并实现抽象类
小米:
public class MIBrandFactory : AbstractFactory
{
public override IMIBrand GetMIBrand(string type)
{
IMIBrand brand = null;
switch (type)
{
case "Phone":
brand = new MIPhone();
break;
case "USB":
brand = new USBStorage();
break;
default:
break;
}
return brand;
}
public override IMorningLight GetMorningLight(string type)
{
return null;
}
}
晨光:
public class MorningLightFactory : AbstractFactory
{
public override IMIBrand GetMIBrand(string type)
{
return null;
}
public override IMorningLight GetMorningLight(string type)
{
IMorningLight brand = null;
switch (type)
{
case "NoteBook":
brand = new NoteBook();
break;
case "Pen":
brand = new Pen();
break;
default:
break;
}
return brand;
}
}
5、创建超级工厂(工厂生成器)
public class FactoryProducter
{
public static AbstractFactory GetFactory(string facType)
{
AbstractFactory factory = null;
switch (facType)
{
case "MIBrand":
factory = new MIBrandFactory();
break;
case "MorningLight":
factory = new MorningLightFactory();
break;
default:
break;
}
return factory;
}
}
6、调用:
static void Main(string[] args)
{
Console.WriteLine("抽象工厂模式");
// 获取小米品牌工厂
AbstractFactory mi_Factory = FactoryProducter.GetFactory("MIBrand");
// 获取小米品牌下得小米手机商品
IMIBrand mi_Phone = mi_Factory.GetMIBrand("Phone");
// 调用方法
mi_Phone.PrintName();
// 获取晨光品牌工厂
AbstractFactory morning_Factory = FactoryProducter.GetFactory("MorningLight");
// 获取晨光品牌下得笔记本商品
IMorningLight morning_Phone = morning_Factory.GetMorningLight("NoteBook");
// 调用方法
morning_Phone.PrintIn();
Console.ReadLine();
}