码迷,mamicode.com
首页 > 编程语言 > 详细

python设计模式第五天【单例模式】

时间:2018-08-12 15:48:13      阅读:159      评论:0      收藏:0      [点我收藏+]

标签:target   return   ==   用户创建   ret   懒汉   char   eth   懒汉式   

1. 定义

一个类只有一个实例,提供访问该实例的全局方法

2.应用场景

(1)多线程之间共享对象资源

(2)整个程序空间中的全局变量,共享资源

(3)大规模程序的节省创建对象的时间

 

3.代码实现(使用饿汉式)

#!/usr/bin/env python
# _*_ coding: UTF-8 _*_

from threading import Thread

class Person(object):

    __instance = None

    def __init__(self):
        pass

    ‘‘‘第一种实现方法,使用python类的魔术方法,在用户创建对象是调用‘‘‘
    def __new__(cls, *args, **kwargs):
        if cls.__instance is None:
            cls.__instance = object.__new__(cls, *args, **kwargs)
        return cls.__instance

    ‘‘‘第二种实现方法,使用静态方法获取对象‘‘‘
    @staticmethod
    def getInstance():
        if Person.__instance is None:
            Person.__instance = Person()
        return Person.__instance


def foo():
    print Person()

def bar():
    print Person.getInstance()


if __name__ == "__main__":
    person1 = Person()
    print person1

    person2 = Person()
    print person2

    person3 = Person()
    print person3

    person4 = Person.getInstance()
    print person4

    person5 = Person.getInstance()
    print person5


    for i in range(5):
        thread = Thread(target=foo(), args=())
        thread.start()
        thread.join()

    for j in range(5):
        thread = Thread(target=bar(), args=())
        thread.start()
        thread.join()

结果:

/Users/liudaoqiang/PycharmProjects/numpy/venv/bin/python /Users/liudaoqiang/Project/python_project/day5_singleton/singleton_test.py
<__main__.Person object at 0x107d331d0>
<__main__.Person object at 0x107d331d0>
<__main__.Person object at 0x107d331d0>
<__main__.Person object at 0x107d331d0>
<__main__.Person object at 0x107d331d0>
<__main__.Person object at 0x107d331d0>
<__main__.Person object at 0x107d331d0>
<__main__.Person object at 0x107d331d0>
<__main__.Person object at 0x107d331d0>
<__main__.Person object at 0x107d331d0>
<__main__.Person object at 0x107d331d0>
<__main__.Person object at 0x107d331d0>
<__main__.Person object at 0x107d331d0>
<__main__.Person object at 0x107d331d0>
<__main__.Person object at 0x107d331d0>

Process finished with exit code 0

注意:

(1)还可以使用懒汉式实现,即刚开始让__instance = Person()

 

python设计模式第五天【单例模式】

标签:target   return   ==   用户创建   ret   懒汉   char   eth   懒汉式   

原文地址:https://www.cnblogs.com/liuzhiqaingxyz/p/9462871.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!