个人理解
跟工厂方法思路几乎一样,只不过Factory能多create另外一种product
UML类图

代码实现
abstract class ProductA { }
abstract class ProductB { }
class ProductA_1 : ProductA { }
class ProductA_2 : ProductA { }
class ProductB_1 : ProductB { }
class ProductB_2 : ProductB { }
abstract class Factory
{
public abstract ProductA CreateProductA();
public abstract ProductB CreateProductB();
}
class Factory1 : Factory
{
public override ProductA CreateProductA()
{
return new ProductA_1();
}
public override ProductB CreateProductB()
{
return new ProductB_1();
}
}
class Factory2 : Factory
{
public override ProductA CreateProductA()
{
return new ProductA_2();
}
public override ProductB CreateProductB()
{
return new ProductB_2();
}
}
Python代码实现
class BaseProductA(object):
pass
class ProductA1(BaseProduct):
pass
class ProductA2(BaseProduct):
pass
class BaseProductB(object):
pass
class ProductB1(BaseProduct):
pass
class ProductB2(BaseProduct):
pass
class ProductFactory(object):
def GetProductA(self):
raise NotImplementedError("abstract method")
def GetProductB(self):
raise NotImplementedError("abstract method")
class ProductFactory1(ProductFactory):
def GetProductA(self):
return ProductA1()
def GetProductB(self):
return ProductB1()
class ProductFactory2(ProductFactory):
def GetProductA(self):
return ProductA2()
def GetProductB(self):
return ProductB2()
if __name__== "__main__":
factory1 = ProductFactory1()
factory2 = ProductFactory2()
productA = factory1.GetProductA()
productB = factory1.GetProductB()
productA = factory2.GetProductA()
productB = factory2.GetProductB()
本文深入探讨了抽象工厂模式的设计理念,通过对比工厂方法模式,详细解释了抽象工厂如何创建多种不同类型的产品实例。提供了C#与Python两种语言的具体实现示例,并展示了如何根据不同需求选择合适的工厂来创建产品。
1019

被折叠的 条评论
为什么被折叠?



