python设计模式---创建型之单例模式

Posted aguncn

tags:

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

数据结构和算法是基本功,

设计模式是最佳实现。

作为程序员,必须有空了就练一练哈。

技术图片

# coding = utf-8

"""
# 经典单例
class Singleton:
    def __new__(cls):
        if not hasattr(cls, ‘instance‘):
            cls.instance = super(Singleton, cls).__new__(cls)
        return cls.instance


s1 = Singleton()
print(‘Object created‘, s1)
s2 = Singleton()
print(‘Object created‘, s2)

# 单例模式中的懒汉式实例化
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


s1 = Singleton()
print("Object created ", Singleton.get_instance())
s2 = Singleton()



# 通过__init__实现Monostate单态模式
class Borg:
    __shared_stat = {"1": "one"}

    def __init__(self):
        self.x = 1
        self.__dict__ = self.__shared_stat
        pass


b1 = Borg()
b2 = Borg()
b1.x = 4

print(‘Borg Object b1: ‘, b1)
print(‘Borg Object b2: ‘, b2)
print(‘Object State b1: ‘, b1.__dict__)
print(‘Object State b2: ‘, b2.__dict__)



# 通过__new__实现Monostate单态模式
class Borg:
    __shared_stat = {"1": "one"}

    def __new__(cls, *args, **kwargs):
        obj = super().__new__(cls, *args, **kwargs)
        obj.__dict__ = cls.__shared_stat
        return obj


b1 = Borg()
b2 = Borg()
b1.x = 4

print(‘Borg Object b1: ‘, b1)
print(‘Borg Object b2: ‘, b2)
print(‘Object State b1: ‘, b1.__dict__)
print(‘Object State b2: ‘, b2.__dict__)

# 元类示例
class MyInt(type):
    def __call__(cls, *args, **kwargs):
        print(‘****Here is my int****‘, args)
        print(‘Now do whatever you want with this object...‘)
        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().__call__(*args, **kwargs)
        return cls._instances[cls]


class Logger(metaclass=MetaSingleton):
    pass


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


# sqlite3数据库连接单例
import sqlite3


class MetaSingleton(type):
    _instances = {}

    def __call__(cls, *args, **kwargs):
        if cls not in cls._instances:
            cls._instances[cls] = super().__call__(*args, **kwargs)
        return cls._instances[cls]


class Database(metaclass=MetaSingleton):
    connection = None
    cursor = None

    def connect(self):
        if self.connection is None:
            self.connection = sqlite3.connect(‘db.sqlite3‘)
            self.cursor = self.connection.cursor()
        return self.cursor


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

print(‘Database Objects DB1‘, db1)
print(‘Database Objects DB2‘, db2)
"""


# 监控服务器单例
class HealthCheck:
    _instance = None
    _servers = []

    def __new__(cls, *args, **kwargs):
        print(====new====)
        if not cls._instance:
            cls._instance = super().__new__(cls, *args, **kwargs)
            print(cls._instance)
        print(=======cls._instance========, cls._instance)
        return cls._instance

    # def __init__(self):
    #    print(‘====init====‘)
    #    self._servers = []

    def add_server(self):
        self._servers.append(Server 1)
        self._servers.append(Server 2)
        self._servers.append(Server 3)
        self._servers.append(Server 4)
        self._servers.append(Server 5)
        print(self._servers)

    def change_server(self):
        self._servers.pop()
        self._servers.append(Server 6)
        print(self._servers)

    def __len__(self):
        return len(self._servers)


hc1 = HealthCheck()
hc1.add_server()
print(Schedule health check for server (1)...)
for i in range(len(hc1)):
    print(Checking , hc1._servers[i])

hc2 = HealthCheck()
hc2.change_server()
print(Schedule health check for server (2)...)
for i in range(len(hc2)):
    print(Checking , hc2._servers[i])

 

C:UsersSahara.virtualenvs	estScriptspython.exe C:/Users/Sahara/PycharmProjects/test/python_search.py
====new====
<__main__.HealthCheck object at 0x00000000021E35F8>
=======cls._instance======== <__main__.HealthCheck object at 0x00000000021E35F8>
[Server 1, Server 2, Server 3, Server 4, Server 5]
Schedule health check for server (1)...
Checking  Server 1
Checking  Server 2
Checking  Server 3
Checking  Server 4
Checking  Server 5
====new====
=======cls._instance======== <__main__.HealthCheck object at 0x00000000021E35F8>
[Server 1, Server 2, Server 3, Server 4, Server 6]
Schedule health check for server (2)...
Checking  Server 1
Checking  Server 2
Checking  Server 3
Checking  Server 4
Checking  Server 6

Process finished with exit code 0

 

以上是关于python设计模式---创建型之单例模式的主要内容,如果未能解决你的问题,请参考以下文章

Python设计模式之单例模式

python之单例模式

设计模式之单例模式

python 3 基础之单例模式

python基础之单例模式

设计模式之单例模式与工厂模式的Python实现