Python设计模式(三)--抽象工厂模式

来源:互联网 发布:淘宝云客服考试试题 编辑:程序博客网 时间:2024/06/01 19:16

抽象工厂

抽象工厂模式(英语:Abstract factory pattern)是一种软件开发设计模式。抽象工厂模式提供了一种方式,可以将一组具有同一主题的单独的工厂封装起来。
在正常使用中,客户端程序需要创建抽象工厂的具体实现,然后使用抽象工厂作为接口来创建这一主题的具体对象。客户端程序不需要知道(或关心)它从这些内部的工厂方法中获得对象的具体类型,因为客户端程序仅使用这些对象的通用接口。抽象工厂模式将一组对象的实现细节与他们的一般使用分离开来。[1]

概念

抽象工厂模式的实质是“提供接口,创建一系列相关或独立的对象,而不指定这些对象的具体类。

UML图

这里写图片描述

实现

#!/usr/bin/env python#-*- coding:utf-8 -*-########################################################    #    文件名 :   abstruct_factory.py#    作者   :   WangYi#  电子邮箱 :   gzytemail@126.com#    日期   :   2017/04/12 17:17:22#    #    描述   :   抽象工厂模式## Abstruct Product Aclass APA(object):    def __init__(self):        pass    def create(self):        pass# Abstruct Product Bclass APB(object):    def __init__(self):        pass    def create(self):        pass# Product A_1class PA1(APA):    def __init__(self):        print("create PA1 instance")    def create(self):        print("making a Product A1")# Product A_1class PA2(APA):    def __init__(self):        print("create PA2 instance")    def create(self):        print("making a Product A2")# Product B_1class PB1(APB):    def __init__(self):        print("create PB1 instance")    def create(self):        print("making a Product B1")# Product B_2class PB2(APB):    def __init__(self):        print("create PB2 instance")# Abstruct Factory Classclass AF(object):    def __init__(self):        pass    def make_product_a(self):        pass    def make_product_b(self):        pass# Factory Aclass FactoryA(AF):    def __init__(self):        pass    def make_product_a(self):        return PA1()    def make_product_b(self):        return PB1()# Factory Bclass FactoryB(AF):    def __init__(self):        pass    def make_product_a(self):        return PA2()    def make_product_b(self):        return PB2()def product_process():    for cls in [FactoryA, FactoryB]:        f = cls()        # get Product A instance        a = f.make_product_a()        a.create()        # get Product B instance        b = f.make_product_b()        b.create()if __name__ == "__main__":    product_process()

结果如下:

create PA1 instancemaking a Product A1create PB1 instancemaking a Product B1create PA2 instancemaking a Product A2create PB2 instancemaking a Product B2
0 0
原创粉丝点击