//创建北京抽象类
public abstract class DaMi{
public abstract void Print(); }//创建上海抽象类
public abstract class BaiMian { public abstract void Print(); }//创建抽象工厂类,提供两个不同地方的的接口
public abstract class AbstractFactory {
public abstract DaMi CreateDaMi(); public abstract BaiMian CreateBaiMian(); }//北京工厂
public class BeiJingFactory : AbstractFactory {
public override DaMi CreateDaMi() { return new BeiJingDaMi(); }public override BaiMian CreateBaiMian()
{ return new BeiJingBaiMian(); } }//上海工厂
public class ShangHaiFactory:AbstractFactory {
public override DaMi CreateDaMi(){
return new ShangHaiDaMi();
}
public override BaiMian CreateBaiMian(){
return new ShangHaiBaiMian();
}
}
public class BeiJingDaMi:DaMi{
public override void Print(){
Console.WriteLine("北京大米");
}
}
public class BeiJingBaiMian:BaiMian{
public override void Print(){
Console.WriteLine("北京白面");
}
}
public class ShangHaiDaMi:DaMi{
public override void Print(){
Console.WriteLine("上海大米");
}
}
public class ShangHaiBaiMian:BaiMian{
public override void Print(){
Console.WriteLine("上海白面");
}
}
调用:
AbstractFactory beijingFactory=new BeiJingFactory ();
DaMi beijingDaMi=beijingFactory.CreateDaMi();
beijingDaMi.Print();
BaiMian beijingBaiMian=beijingFactory.CreateBaiMian();
beijingBaiMian.Print();
AbstractFactory shanghaiFactory=new ShangHaiFactory();
shanghaiFactory.CreateDaMi().Print();
shanghaiFactory.CreateBaiMian().Print();
抽象工厂模式:提供一个创建产品的接口来负责创建相关或依赖的对象,而不具体明确指定具体类
抽象工厂对于系列产品的变化支持 “开放——封闭”原则(指的是要求系统对扩展开放,对修改封闭),扩展起来非常简便,但是,抽象工厂对于添加新产品这种情况就不支持”开放——封闭 “原则,这也是抽象工厂的缺点所在.