The bus is one of the public communication solutions for transmitting data, control signals and other information between various functional components or devices of the computer. Now assume the following scenario: a central processing unit (CPU) is connected to a semaphore through a certain protocol bus. The semaphore has 64 colors that can be set. There are three threads running on the CPU, all of which can control the semaphore, and The color of this signal light can be set independently. Abstract the protocol details (represented by printing), and how to implement the thread's control logic for signals, etc.
Adding thread locks for control is undoubtedly the first method that comes to mind, but the control of locks by each thread undoubtedly increases the coupling between modules. Next, we will use Single case pattern in Design Pattern to solve this problem.
What is singleton pattern? The singleton pattern means: ensuring that a class has only one instance and providing a global access point to access it. Specifically in this example, the busobject is a singleton, which has only one instance. Each thread has only one global access point for the bus, that is, the only instance.
PythonThe code is as follows:
#encoding=utf8import threading import time#这里使用方法new来实现单例模式class Singleton(object):#抽象单例 def new(cls, *args, **kw): if not hasattr(cls, '_instance'): orig = super(Singleton, cls) cls._instance = orig.new(cls, *args, **kw) return cls._instance#总线class Bus(Singleton): lock = threading.RLock() def sendData(self,data): self.lock.acquire() time.sleep(3) print "Sending Signal Data...",data self.lock.release()#线程对象,为更加说明单例的含义,这里将Bus对象实例化写在了run里class VisitEntity(threading.Thread): my_bus="" name="" def getName(self): return self.name def setName(self, name): self.name=name def run(self): self.my_bus=Bus() self.my_bus.sendData(self.name)if name=="main": for i in range(3): print "Entity %d begin to run..."%i my_entity=VisitEntity() my_entity.setName("Entity_"+str(i)) my_entity.start()
The running results are as follows:
Entity 0 begin to run...
Entity 1 begin to run...
Entity 2 begin to run...
Sending Signal Data... Entity_0
Sending Signal Data... Entity_1
Sending Signal Data... Entity_2
During the running of the program, three threads simultaneously Run (the first three lines of the running result are printed out quickly), and then the bus resources are occupied respectively (the last three lines are printed every 3 seconds). Although it looks like the bus is instantiated three times, there is actually only one instance in memory.
Single-case pattern
The single-case pattern is a relatively simple type of all design patterns. Its definition is as follows: Ensure a class has only one instance, and provide a global point of access to it .(Guarantee that a certain class has only one instance and only one access point globally)
Advantages and applications of singleton mode
Advantages of singleton mode:
1. Since singleton mode Example mode requires that there is only one instance in the world, so it can save a lot of memory space;
2. There is only one access point in the world, which can better control data synchronization and avoid multiple occupancy;
3. Single Examples can be stored in memory to reduce system overhead.
Application examples of singleton mode:
1. Generate a globally unique serial number;
2. Access globally multiplexed unique resources, such as disks, buses, etc.;
3. Occupied by a single object Too many resources, such as databases, etc.;
4. Global unified management of the system, such as Task Manager under Windows;
5. Website counter.
Disadvantages of the singleton mode
1. The expansion of the singleton mode is relatively difficult;
2. It assigns too many responsibilities to the singleton, which violates the singleton pattern to some extent. Responsibility principle (the six principles will be discussed later);
3. The singleton mode is the first thing to be completed in the concurrent collaboration software module, so it is not conducive to testing;
4. The singleton mode is used in certain situations This will lead to "resource bottlenecks".
The above is the detailed content of Introducing Python's singleton pattern. For more information, please follow other related articles on the PHP Chinese website!