python 设计模式

一、单例模式:

确保一个类只有一个实例, 并提供全局访问点. 

class Single:
    """ 单例模式 """
    _singleton = None

    def __new__(cls, *args, **kwargs):
        if not cls._singleton:
            cls._singleton = super(Single, cls).__new__(cls, *args, **kwargs)
        return cls._singleton

 

二、共享模式:

能解决单例模式的多继承问题

class Borg:
    """ 共享模式一 """
    _we_are_one = {}

    def __new__(cls, *args, **kwargs):
        self = object.__new__(cls, *args, **kwargs)
        self.__dict__ = cls._we_are_one
        return self


def borg(cls):
    """ 共享模式二(装饰器版) """
    cls._state = {}
    orig_init = cls.__init__

    def new_init(self, *args, **kwargs):
        self.__dict__ = cls._state
        orig_init(self, *args, **kwargs)

    cls.__init__ = new_init
    return cls


@borg
class A:
    pass

 

三、策略模式


from hashlib import md5,sha1

class StreamHasher:
	""" 策略模式
		>>> from hashlib import md5,sha1
		>>> m5=StreamHasher(md5)
		>>> m5(open('m模式.py'))
		'34ef7b42207e610a9948eadb34c5d994'
		>>> s1=StreamHasher(sha1)
		>>> s1(open('m模式.py'))
		'ab0b4c103db64e85993e73452d93141c01504c54'
	"""
	def __init__(self,algorithm,chunk_size=4096):
		self.chunk_size = chunk_size
		self.hash = algorithm()

	def __call__(self, stream):
		for chunk in iter(lambda: stream.read(self.chunk_size),''):
			self.hash.update(chunk.encode('utf-8'))
		return self.hash.hexdigest()


四、原型模式



import copy

class Prototype:
	""" 原型模式 """
	def clone(self):
		return copy.deepcopy(self)

		

 

你可能感兴趣的:(算法与数据结构)