实现:创建一系列相关或相互依赖对象的接口,而无需指定它们具体的类。
public abstract class AbstractFactory(){
public abstract A CreateA();
public abstract B CreateB();
}
public class 1Factory : AbstractFactory{
public overrid A CreateA(){
return new 1A();
}
public overrid B CreateB(){
return new 1B();
}
}
public class 2Factory:AbstractFactory{
public overrid A CreateA(){
return new 2A();
}
public overrid B CreatedB(){
return new 2B();
}
}
public class 1A : A{
public override void Create{
.....
}
}
public class 2A : A{
public override void Create{
.....
}
}
public class 1B :B{
public override void Create{
.....
}
}
public class 2B :B{
public override void Create{
.....
}
}
public abstract class A{
public abstract void Create();
}
public abstract class B{
public abstract void Create();
}
public class Client{
static void Main(){
var 1factory = new 1Factory();
1factory.CreateA.Create();
1factory.CreateB.Create();
var 2factory = new 2Factory();
2factory.CreateA.Create();
2factory.CreateB.Create();
}
}
优点:将系列产品的创建工作延迟到具体工厂的子类中,减少客户端代码与具体产品类间的依赖,从而降低了系统的耦合度。
缺点:如果需要新增新产品,此时就必须修改抽象工厂的接口,违背OCP原则。