设计模式之构造模式

使用工厂模式时,每个工厂类中属性和实现都是定义好的,比如有一个小米手机的工厂,生产Mi9和MIX3,你要一个Mi9就给你个Mi9,参数属性都是一样的

如图:

  

代码:

  

# -*- coding=utf-8 -*-
class MiFactory(object):
    class Mi9(object):
        def __init__(self):
            self.RAM = '8G'
            self.ROM = '128G'
            self.CPU = '855'

        def __str__(self):
            """
            返回对象描述
            :return: 对象的描述
            """
            return '小米9生产,运存:{},内存:{},CPU:{}'.format(self.RAM, self.ROM, self.CPU)

    class MIX3(object):
        def __init__(self):
            self.RAM = '6G'
            self.ROM = '128G'
            self.CPU = '845'

        def __str__(self):
            """
            返回对象描述
            :return: 对象的描述
            """
            return '小米MIX3生产,运存:{},内存:{},CPU:{}'.format(self.RAM, self.ROM, self.CPU)

    def production(self, type):
        """
        根据手机型号使用对应的生产方法进行生产手机
        :param type: 手机型号
        :return:
        """
        try:
            product_line = getattr(MiFactory, type)
            return product_line()
        except AttributeError:
            print "未知型号,不能生产"
            return '没有生产线给{}'.format(type)

# 生产一个Mi9
Factory = MiFactory()
mi9 = Factory.production('Mi9')
print mi9

# output
    小米9生产,运存:8G,内存:128G,CPU:855

# 生产一个Mi8
Factory = MiFactory()
mi8 = Factory.production('Mi8')
print mi8

#output:
    未知型号,不能生产
    没有生产线给Mi8

因为生产线已经固定好了,生产的手机也是一样的,但是如果希望可以定制手机配置就不行了,试试构造模式吧!

  如图:

  代码:

    

# -*- coding:utf-8 -*-
class Phone(object):
    """
    手机类 是需要被实例化的类对象,属性配置跟生产线参数设置有关
    """

    def __init__(self):
        self.name = None
        self.RAM = None
        self.ROM = None
        self.CPU = None

    def __str__(self):
        return '生产了手机:{},配置:RAM {}, ROM {}, CPU {}'.format(self.name, self.RAM, self.ROM, self.CPU)


class ProductLine(object):
    """
    生产线 可以根据传入的参数不同,对手机的配置做不同的处理
    """

    def __init__(self):
        self.phone = Phone()

    def printing_logo(self, name):
        self.phone.name = name

    def install_RAM(self, RAM):
        self.phone.RAM = RAM

    def install_ROM(self, ROM):
        self.phone.ROM = ROM

    def install_CPU(self, CPU):
        self.phone.CPU = CPU


class Engineer(object):
    """
    工程师 负责根据配置需要调整生产线参数
    """

    def __init__(self):
        self.product_line = ProductLine()

    def operation(self, name, RAM, ROM, CPU):
        self.product_line.printing_logo(name)
        self.product_line.install_RAM(RAM)
        self.product_line.install_ROM(ROM)
        self.product_line.install_CPU(CPU)

    # 返回生产的phone的信息
    # property 将方法变为属性调用
    @property
    def phone(self):
        return self.product_line.phone


engineer = Engineer()
engineer.operation('mi9', '8G', '128G', '骁龙855')
print engineer.phone


# output:
    生产了手机:mi9,配置:RAM 8G, ROM 128G, CPU 骁龙855

    

  

原文地址:https://www.cnblogs.com/wangbaojun/p/11316433.html