Python中的几种设计模式

  1. 单例模式:
    法一:通过类的new()方法,但是个人感觉没有装饰器方便
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
class Singleton(object):
__instance = None

def __init__(self):
pass

def __new__(cls, *args, **kwd):
if Singleton.__instance is None:
Singleton.__instance = object.__new__(cls, *args, **kwd)
return Singleton.__instance

class MyClass(Singleton):
aa = 88

instance1 = MyClass()
instance2 = MyClass()
print id(instance1)
print id(instance2)
139984856635600
139984856635600
  1. 用装饰器来实现
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    def singleton(cls, *args, **kw):
    instances = {}
    def _singleton():
    if cls not in instances:
    instances[cls] = cls(*args, **kw)
    return instances[cls]
    return _singleton

    @singleton
    class MyClass1(object):
    aa = 56
    instance1 = MyClass1()
    instance2 = MyClass1()
    print id(instance1)
    #139764123790288
    print id(instance2)
    #139764123790288