Python- Programming: Singleton

Singleton

  Singleton (Singleton Pattern) belongs created schema, which provides the best way to create the object. This model involves a single class that is responsible for creating your own objects, while ensuring that only a single object is created, and provides the only way to access the object.

Features:

  Example 1. A single instance of a class can have

  2. Simple Interest class must create their own unique instance

  3. singleton class must provide this instance to other objects

Solve the problem:

  The use of a global class, frequent founded destroyed.

scenes to be used:

  The need to control the number of instances, time-saving system resources.

Creation Method:

  Determining whether there is currently singleton class instance, if the instance is returned is not created

Actual usage:

  1. Create an object need to consume too many resources, such as I / O connections to the database

  2.Web the counter, not once in the database are refreshed every Riga, first with simple interest cached

  3. Design of the thread pool is generally only a single embodiment mode, the thread control easy

  4. Application of the log application, what is generally implemented with a single mode of embodiment, since the shared log file remains open, because only one instance to operate, or not additional content.

Code:

1. Module

# 1. Module: 
"" " the Python module is a natural single-mode embodiment, as introduced in the first module, it generates .pyc files, 
when introducing the second time, will load .pyc file directly, and module code will not be executed again. 
Therefore, we need the relevant data and functions are defined in a module, you can get a singleton object up. "" " 


class Singleton (Object): 

    DEF foo (Self):
         Pass 


Singleton = the Singleton () 

# above code is stored in the file mysingleton.py, is to be used, this file import objects directly in other files, i.e., the object is a singleton object 
# from MySingleton import Singleton

2. metaclass metaclass

# 2 metaclasses the metaclass that 
"" " 
1. When the category type created, creating class, the __init__ method of automatic execution type, class instantiation performed __call__ type of method 
2. The objects created by a class object is created when, like the __init__ method automatically performed, the object () method performs class __call__ 
"" " 


class Singleton (type):
     " "" 
    judge the class attribute in metaclass __instance __call__ method of Singleton, if __instance to None, 
    explain the class has not been instantiated, then call the parent class metaclass (metaclass is a type of sub-class) type of __call__ method, 
    while assigned to the cls .__ instance. If cls .__ instance is not None , 
    described class has been instantiated, the instance of the class stored in the class attribute cls .__ instance, i.e. directly before the single-mode embodiment returned. 
    "" " 
    DEF  the __init__ (CLS, args *, ** kwargs): 
        CLS. __instance = none 
        Super (). __init__ (* args,**kwargs)

    def __call__(cls, *args, **kwargs):
        if not cls.__instance:
            cls.__instance = super().__call__(*args, **kwargs)
        return cls.__instance


class Foo(metaclass=Singleton):
    pass


foo1 = Foo()
foo2 = Foo()
print(foo1 is foo2)

3. Use the method __new__

# 3. Use __new__ method 
class Singleton (Object):
     "" " When we instantiate an object, the method is to perform a __new__ class (we did not write the default call object .__ new__), 
    instantiate object, and then re-execute the class __init__ method, this object is initialized, 
    all based on this we can achieve a singleton "" " 

    DEF  __new__ (CLS, * args, ** kwargs):
         IF  not hasattr (CLS, ' _instance ' ):   # key is instantiated every time we return this same _instance objects 
            cls._instance = Super (). __new__ (CLS)
         return cls._instance 


class Foo (Singleton):
     DEF  __init__ (Self):
         Pass 


foo1= Foo()
foo2 = Foo()
print(foo2 is foo1)

4. decorator

# 4. decorator 
DEF Singleton (CLS): 
    instance = {} 

    DEF get_singleton (* args, ** kwargs):
         IF CLS Not  in instance:                      # determines whether there is a dictionary 
            instance [cls] = cls (* args, * kwargs *)     # here corresponds to Foo () 
        return instance [CLS] 

    return get_singleton 


@Singleton 
class Foo:
     Pass 


foo1 = Foo () 
foo2 = Foo ()
 Print (foo1 IS foo2)

 

Guess you like

Origin www.cnblogs.com/zivli/p/11442670.html