设计模式:Python实现创建型模式

一、常见创建型设计模式

 单例模式(Borg/Singleton): 一个类只能创建同一个对象
工厂模式(Factory):解决对象创建问题
构造模式(Builder):解决复杂对象的创建
原型模式(Prototype):通过原型克隆创建新的实例
对象池模式(Pool): 预先分配同一类型的一组实例
惰性计算模式(Lazy Evaluation) : 延时计算

二、单例模式实现 

只希望一个类只有一个实例需要用到单例模式

  • 在创建实例的时候判断是否包含'_instance'属性,如果不包含则调用父类方法__new__(),包含则直接返回实例
class Singleton(object):
    def __new__(cls, *args, **kwargs):
        # print(hasattr(cls,'_instance'))
        if not hasattr(cls, '_instance'):
            cls._instance = object.__new__(cls, *args, **kwargs)
        return cls._instance


class MyClass(Singleton):
    a = 1


# my_cls对象的a属性修改之后,my_cls2的属性也随之修改

my_cls = MyClass()
my_cls.a = my_cls.a+1
print(my_cls.a)

my_cls2 = MyClass()
print(id(my_cls),id(my_cls2))
print(my_cls2.a)

输出结果

三、工厂模式实现

提供统一的对象创建方式需要用到工厂模式

  • 通过统一的方法创建对象,根据传入的参数不同返回不同的对象
class DogToy:
    def speak(self):
        print('wangwang')


class CatToy:
    def speak(self):
        print('miaomiao')


def toy_factory(toy_type):
    if toy_type == 'dog':
        return DogToy()
    elif toy_type == 'cat':
        return CatToy()


instance = toy_factory('dog')
instance.speak()

 输出结果:

四、构造模式

创建复杂对象需要用到构造模式

  • Computer为复杂对象,ComputerBuild 为复杂对象的构建器,HardwareEngineer 为组装类,
    通过实例化HardwareEngineer,然后传入参数调用construct_computer(*args,**kwargs) 实现构造指定实例
# 一个构造模式的例子
class Computer:
    def __init__(self, serial_number):
        self.serial = serial_number
        self.memory = None
        self.hdd = None
        self.gpu = None


class ComputerBuilder:
    def __init__(self):
        self.computer = Computer('AG23385193')

    def configure_memory(self, amount):
        self.computer.memory = amount

    def configure_hdd(self, hdd_amount):
        self.computer.hdd = hdd_amount

    def configure_gpu(self, gpu_amount):
        self.computer.gpu = gpu_amount


class HardwareEngineer:
    def __init__(self):
        self.builder = None

    def construct_computer(self, memory, hdd, gpu):
        self.builder = ComputerBuilder()
        self.builder.configure_memory(memory)
        self.builder.configure_hdd(hdd)
        self.builder.configure_gpu(gpu)

    @property
    def computer(self):
        return self.builder.computer


engineer = HardwareEngineer()
engineer.construct_computer(memory=20, hdd=500, gpu=8)
computer = engineer.computer
print(computer.memory)

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值