#!/usr/bin/env python3
# _*_ coding:utf-8 _*_
# ========================================================
# Module : singleton
# Author : luting
# Create Date : 2018/6/3
# Amended by : luting
# Amend History : 2018/6/3
# ========================================================
# 单例 => 确保类只有一个对象被创建, 为对象提供一个访问点,以使程序可以全局访问该对象。控制共享资源的并行访问
# 使构造函数私有化,并创建一个静态方法来完成对象的初始化,这样,对象在第一次被创建时,此后,这个类将返回同一个对象
# 经典单例模式实现
class Singleton(object):
def __new__(cls):
if not hasattr(cls, 'instance'):
cls.instance = super(Singleton, cls).__new__(cls)
return cls.instance
s = Singleton()
print(s)
s1 = Singleton()
print(s1)
# 懒汉式实例化
class Singleton:
__instance = None
def __init__(self):
if not Singleton.__instance:
print('__init__ method called')
else:
print('instance already created', self.get_instance())
@classmethod
def get_instance(cls):
if not cls.__instance:
cls.__instance = Singleton()
return cls.__instance
s = Singleton()
print(s)
s1 = Singleton()
print(s1)
# Monostate单例模式
class Borg:
__shared_state = {'1': '2'}
def __init__(self):
self.x = 1
self.__dict__ = self.__shared_state
pass
b = Borg()
b1 = Borg()
b.x = 4
print(b, b1, b.__dict__, b1.__dict__)
class Borg(object):
__shared_state = {}
def __new__(cls, *args, **kwargs):
obj = super(Borg, cls).__new__(cls, *args, **kwargs)
obj.__dict = cls.__shared_state
return obj
# 单例元类
class MetaSingleton(type):
__instances = {}
def __call__(cls, *args, **kwargs):
if cls not in cls.__instances:
cls.__instances[cls] = super(MetaSingleton, cls).__call__(*args, **kwargs)
return cls.__instances[cls]
class Login(metaclass=MetaSingleton):
pass
l = Login()
l1 = Login()
print(l, l1)