单例模式的python实现
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 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 | # 本实例主要介绍单例模式 # 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.可能影响其他类 |
分类:
Design patterns
标签:
设计模式
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· 单线程的Redis速度为什么快?