Create schema (IV) singleton

Singleton (Singleton Pattern): to ensure that only one instance of a particular class, and to instantiate the instance of the entire system and to provide this class is called singleton class that provides global access method.

  • Singleton ensure only one instance of a particular class, and to instantiate the instance of the entire system and to provide this class is called singleton class that provides global access method. Singletons points are three: First, only one instance of a class; second, it must create an instance of its own; it must provide their own three in this example the entire system. Singleton pattern is an object to create schema.
  • Singleton embodiment contains only a single character: implemented in a single embodiment only one class internally generated instance, and it provides a static factory method, so that customers can use its unique instance; in order to prevent them externally instantiated, the The constructor designed to be private .
  • Singleton object is to ensure that only one instance of a class, and it provides access to a global access point. Singleton class has a private constructor, to ensure that users can not instantiate it directly through the new keyword. In addition, the model contains a static private member variables public static factory method. The existence of the factory method is responsible for inspection and instantiate instances of their own, and then stored in a static member variables in order to ensure that only one instance is created.
  • Singletons main advantage is to provide controlled access to a single instance and may save system resources; its main drawback is that because of the lack of abstraction and difficult to extend, and heavy duty singleton class.
  • Singleton applicable comprising: a system requires only one instance of an object; a single instance of the class calls the customer is only permitted using a public access point.
# - * - Coding: UTF-8 - * - 

class Singleton (Object): 

    DEF  __new__ (CLS, * args, ** kw):
         '' ' Are there private property _instance class judgment, if not then create a new instance, or return directly _instance, that is, create an instance of the object before '' ' 
        IF  not hasattr (CLS, ' _instance ' ): 
            ORG = Super (Singleton, CLS)
             ' '' will be assigned to the newly created instance of the class _ private property instance '' ' 
            cls._instance = ORG. __new__ is (CLS, args *, ** kW)
         return cls._instance 

S1 = the Singleton () 
S2 = Singleton()


print(s1)
print(s2)

 

Results: two instances of the memory address is the same object

<__main__.Singleton object at 0x0000000001DD3438>
<__main__.Singleton object at 0x0000000001DD3438>

Guess you like

Origin www.cnblogs.com/dxnui119/p/11944930.html