python设计模式(原型模式、单例模式)

学习版本3.5.2

1.原型模式

原型模式就是拷贝一个对象实例去生成一个新的对象,当初始化过程复杂的时候这个方法就很方便。

import copy

class CloneMyself(object):
    def shallow_copy(self):
        return copy.copy(self)

    def deep_copy(self):
        return copy.deepcopy(self)

class ProductA(CloneMyself):
    def __init__(self, name, type, color, time):
        self.name = name
        self.type = type
        self.color = color
        self.time = time

    def print_info(self):
        print(self.name,self.type,self.color,self.time)

if __name__ == "__main__":
    product1 = ProductA("A","1","y","10:00")
    product1.print_info()
    product2 = product1.shallow_copy()
    product2.print_info()
    product3 = product1.deep_copy()
    product3.print_info()

运行结果

A 1 y 10:00
A 1 y 10:00
A 1 y 10:00

2.单例模式

单例模式就是一个类有且只有一个对象实例。

class Singleton(object):
    _instance = None
    def __new__(cls,*args,**kwargs):
        if cls._instance is None:
            cls._instance = object.__new__(cls,*args,**kwargs)
        return cls._instance

    def __init__(self):
        if not hasattr(self,"num"):
            print("create num")
            setattr(self,"num",0)

    def add(self):
        self.num += 1
        print("num:",self.num)

if __name__ == "__main__":
    c1 = Singleton()
    c1.add()
    c2 = Singleton()
    c2.add()

运行结果

create num
num: 1
num: 2


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值