设计模式之单例模式

单例模式

单例模式(Singleton Pattern)是 最简单的设计模式之一。这种类型的设计模式属于创建型模式,它提供了一种创建对象的最佳方式。

这种模式涉及到一个单一的类,该类负责创建自己的对象,同时确保只有单个对象被创建。这个类提供了一种访问其唯一的对象的方式,可以直接访问,不需要实例化该类的对象

注意:

  • 1、单例类只能有一个实例。
  • 2、单例类必须自己创建自己的唯一实例。
  • 3、单例类必须给所有其他对象提供这一实例。

意图:保证一个类仅有一个实例,并提供一个访问它的全局访问点。

主要解决:一个全局使用的类频繁地创建与销毁。

何时使用:当您想控制实例数目,节省系统资源的时候。

 

 

 

实现如下:

方法一:

# coding:utf-8
__author__ = "xiaomagua"


class Singleton():
    _instance = None
    def __init__(self) -> None:
        if not self._instance:
            print("Start Call init")
        else:
            print("__inst has been created", self._instance)

    def __new__(cls, *args, **kwargs):
        """
        _new__()是Python中的一个魔术方法(构造方法)。
        它会在创建类的时候,先于__init__()执行。
        __new__()会在内存中开辟地址,然后传给__init__()。
        zte third-part release-stable
        """
        if not  cls._instance:
            cls._instance = super().__new__(cls)
        return cls._instance

s1 = Singleton()
s2 = Singleton()
print(id(s1),id(s2))


            

 

方法二:

# coding:utf-8
__author__ = "xiaomagua"


class SingleObject:

    _instance = None

    def __init__(self) -> None:
        if not self._instance:
            print("Start Call init")
        else:
            print("__inst has been created", self.get_instance())

    @classmethod
    def get_instance(cls):
        if not cls._instance:
            cls._instance = SingleObject()
        return cls._instance

SingleObject.get_instance()
s1= SingleObject()
s2= SingleObject()

 

posted @ 2022-07-29 11:29  一只小麻瓜  阅读(17)  评论(0编辑  收藏  举报