python设计模式-单例模式

单例模式

(一)什么是单例模式

单例模式(Singleton Pattern)是一种常用的软件设计模式,该模式的主要目的是确保某一个类只有一个实例存在。当你希望在整个系统中,某个类只能出现一个实例时,单例对象就能派上用场。

(二)实现单例的方法

  • 导入模块
  • 使用new方法
  • 使用装饰器

(三)模块

Python 模块在第一次导入时,会生成 .pyc 文件,当第二次导入时,就会直接加载 .pyc 文件,而不会再次执行模块代码。因此,我们只需把相关的函数和数据定义在一个模块中,就可以获得一个单例对象了。

(四)new方法

# -*- coding: utf-8 -*-

__author__ = 'loco_python'


class Person(object):
    _instance = None
    _is_init = False
    # 实现单例模式
    def __new__(cls, *args, **kwargs):
        if not cls._instance:
            # 如果没有创建对象,我们就创建对象
            cls._instance = super(Person, cls).__new__(cls, *args, **kwargs)
        # 无论如何我们只返回一个对象
        return cls._instance

    # 只做一次初始化。
    def __init__(self, name, age):
        if not self._is_init:
            self.name = name
            self.age = age
            self._is_init = True

    def __str__(self):
        return self.name

p1 = Person('xiaohua', 18)
p2 = Person('xiaowang', 19)
# p1和p2同一地址
print id(p1), id(p2)  # 4308349264 4308349264
# 只初始化了第一次
print p1, p2     # xiaohua xiaohua  
    
    
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32

(五)装饰器

__author__ = 'loco_python'

from functools import wraps


def singleton(cls):
    _instance = {}
    @wraps(cls)
    def wrapper(*args, **kwargs):
        if cls not in _instance:
            _instance[cls] = cls(*args, **kwargs)
        return _instance[cls]
    return wrapper

@singleton
class Person:
    def __init__(self):
        pass

p = Person()
p1 = Person()
print id(p), id(p1)   # 4501461760 4501461760
    
    
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
        <link rel="stylesheet" href="https://csdnimg.cn/release/phoenix/template/css/markdown_views-ea0013b516.css">
            </div>

单例模式

(一)什么是单例模式

单例模式(Singleton Pattern)是一种常用的软件设计模式,该模式的主要目的是确保某一个类只有一个实例存在。当你希望在整个系统中,某个类只能出现一个实例时,单例对象就能派上用场。

(二)实现单例的方法

  • 导入模块
  • 使用new方法
  • 使用装饰器

(三)模块

Python 模块在第一次导入时,会生成 .pyc 文件,当第二次导入时,就会直接加载 .pyc 文件,而不会再次执行模块代码。因此,我们只需把相关的函数和数据定义在一个模块中,就可以获得一个单例对象了。

(四)new方法

# -*- coding: utf-8 -*-

__author__ = 'loco_python'


class Person(object):
    _instance = None
    _is_init = False
    # 实现单例模式
    def __new__(cls, *args, **kwargs):
        if not cls._instance:
            # 如果没有创建对象,我们就创建对象
            cls._instance = super(Person, cls).__new__(cls, *args, **kwargs)
        # 无论如何我们只返回一个对象
        return cls._instance

    # 只做一次初始化。
    def __init__(self, name, age):
        if not self._is_init:
            self.name = name
            self.age = age
            self._is_init = True

    def __str__(self):
        return self.name

p1 = Person('xiaohua', 18)
p2 = Person('xiaowang', 19)
# p1和p2同一地址
print id(p1), id(p2)  # 4308349264 4308349264
# 只初始化了第一次
print p1, p2     # xiaohua xiaohua  
  
  
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32

(五)装饰器

__author__ = 'loco_python'

from functools import wraps


def singleton(cls):
    _instance = {}
    @wraps(cls)
    def wrapper(*args, **kwargs):
        if cls not in _instance:
            _instance[cls] = cls(*args, **kwargs)
        return _instance[cls]
    return wrapper

@singleton
class Person:
    def __init__(self):
        pass

p = Person()
p1 = Person()
print id(p), id(p1)   # 4501461760 4501461760
  
  
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
        <link rel="stylesheet" href="https://csdnimg.cn/release/phoenix/template/css/markdown_views-ea0013b516.css">
            </div>

猜你喜欢

转载自blog.csdn.net/myword1314/article/details/81569708