单例模式的python实现

Posted 代码诠释的世界

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了单例模式的python实现相关的知识,希望对你有一定的参考价值。

# 本实例主要介绍单例模式
# 1.什么是单例模式
  # 1. 确保有且只有一个对象被创建
  # 2. 为对象提供一个访问点,以使程序可以全局访问该对象
  # 3. 控制共享资源的并行访问

# 2.单例模式实例
class Singleton(object):
	def __new__(cls):
		if not hasattr(cls, ‘instance‘):
			cls.instance = super(Singleton, cls).__new__(cls)
		return cls.instance

s = Singleton()
print("Object created",s)
s1 = Singleton()
print("Object created",s1)

		
		
# 3.单例设计模式中的懒汉式实例化
class Singleton1:
	__instance = None
	def __init__(self):
		if not Singleton1.__instance:
			print("__init__ method called")
		else:
			print("Instance already created", self.getInstance())
	
	@classmethod
	def getInstance(cls):
		if not cls.__instance:
			cls.__instance = Singleton1()
		return cls.__instance

s = Singleton1()
print("Object created", Singleton1.getInstance())
s1 = Singleton1()

	
# 4.Monostate(Borg) 单态模式
# 所有对象共享相同状态,改变一个实例的状态,另一个实例也会改变
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("Borg object b", b)
print("Borg object b1", b1)
print("Object state b", b.__dict__)
print("Object state b1", b1.__dict__)

# 基于__new__方法本身实现Borg
class BorgNew:
	__shared_state = {}
	def __new__(cls, *args, **kwargs):
		obj = super(BorgNew , cls).__new__(cls, *args, **kwargs)
		obj.__dict__ = cls.__shared_state
		return obj

b = BorgNew()
b1 = BorgNew()
b.x = 4

print("Borg object b", b)
print("Borg object b1", b1)
print("Object state b", b.__dict__)
print("Object state b1", b1.__dict__)
		
	
# 5.单例和元类
# 元类: 元类是一个类的类,这意味着该类是它元类的一个实例
class MyInt(type):
	def __call__(cls, *args, **kwargs):
		print("******Here is MyInt******",args)
		print("How do whatever you want with these objects...")
		return type.__call__(cls, *args, **kwargs)

class int(metaclass=MyInt):
	def __init__(self, x, y):
		self.x = x
		self.y = y

i = int(4, 5)

# 基于元类的单例实现
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 Logger(metaclass=MetaSingleton):
	pass

logger1 = Logger()
logger2 = Logger()
print(logger1, logger2)
	

# 6.单例模式的应用		
# A. 数据库的操作
import sqlite3
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 Database(metaclass=MetaSingleton):
	connection = None
	def connect(self):
		if self.connection is None:
			self.connection = sqlite3.connect(‘db.sqlite3‘)
			self.cursorobj = self.connection.cursor()
		return self.cursorobj

db1 = Database().connect()
db2 = Database().connect()

print("Database objcursor db1", db1)
print("Database objcursor db2", db2)

# 单一的应用可以使用该方法,节约CPU,内存等资源
# 集群化应用, 就需要使用数据库连接池
	
# B.监控服务
class HealthCheck:
	_instances = None
	def __new__(cls, *args, **kwargs):
		if not HealthCheck._instances:
			HealthCheck._instances = super(HealthCheck, cls).__new__(cls, *args, **kwargs)
		return HealthCheck._instances
	
	def __init__(self):
		self._servers = []
	
	def addServer(self):
		self._servers.append("server1")
		self._servers.append("server2")
		self._servers.append("server3")
		self._servers.append("server4")
	
	def changeServer(self):
		self._servers.pop()
		self._servers.append("server5")

hc1 = HealthCheck()
hc2 = HealthCheck()
print(hc1,hc2)

hc1.addServer()
for i in range(4):
	print("checking ", hc1._servers[i])

hc2.changeServer()
for i in range(4):
	print("checking ", hc2._servers[i])
		
						
# 7.单例模式的优缺点
# 优点: 1. 创建有且只有一个对象, 2.节省CPU,内存资源.
# 缺点: 1. 全局变量被误改, 但是别的对象还在引用 2.同一个对象,创建多个引用 3.可能影响其他类

  

以上是关于单例模式的python实现的主要内容,如果未能解决你的问题,请参考以下文章

Python如何实现单例模式

常见设计模式 (python代码实现)

深刻理解Python中的元类(metaclass)以及元类实现单例模式

Java单例模式

Python实现单例模式

一日一技:Python 下面最简单的单例模式写法