抽象工厂模式(Abstract Factory)

本文深入探讨了抽象工厂模式的设计理念,通过对比工厂方法模式,详细解释了抽象工厂如何创建多种不同类型的产品实例。提供了C#与Python两种语言的具体实现示例,并展示了如何根据不同需求选择合适的工厂来创建产品。

个人理解

跟工厂方法思路几乎一样,只不过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()

 

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值