zoukankan      html  css  js  c++  java
  • python与设计模式--单例模式

    https://zhuanlan.zhihu.com/p/31675841

    设计模式分类
    创建类 单例模式、工厂模式、抽象工厂模式、原型模式、建造者模式
    结构类 装饰器模式、适配器模式、门面模式、组合模式、享元模式、桥梁模式
    行为类 策略模式、责任链模式、命令模式、中介者模式、模板模式、迭代器模式、访问者模式、观察者模式、解释器模式、备忘录模式、状态模式

    单例模式

    总线是计算机各种功能部件或者设备之间传送数据、控制信号等信息的公共通信解决方案之一。现假设有如下场景:某中央处理器(CPU)通过某种协议与一个信号灯相连,信号灯有64种颜色可以设置,中央处理器上运行着三个线程,都可以对这个信号灯进行控制,并且可以独立设置该信号灯的颜色。抽象掉协议细节(用打印表示),如何实现线程对信号灯的控制逻辑。

    加线程锁进行控制,五一是最先想到的方法,但是各个线程对锁的控制,无疑加大了模块之间的耦合。下面,我们就用设计模式中的单例模式,来解决这个问题。

    什么是单例模式?单例模式是指:

    import threading
    import time
    
    class Singleton(object):
        def __new__(cls, *args, **kwargs):
            if not hasattr(cls,"_instance"):
                orig = super(Singleton, cls)
                cls._instance = orig.__new__(cls, *args, **kwargs)
            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()
    
    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()
  • 相关阅读:
    Codeforces Round #251 (Div. 2) A
    topcoder SRM 623 DIV2 CatAndRat
    topcoder SRM 623 DIV2 CatchTheBeatEasy
    topcoder SRM 622 DIV2 FibonacciDiv2
    topcoder SRM 622 DIV2 BoxesDiv2
    Leetcode Linked List Cycle II
    leetcode Linked List Cycle
    Leetcode Search Insert Position
    关于vim插件
    Codeforces Round #248 (Div. 2) B. Kuriyama Mirai's Stones
  • 原文地址:https://www.cnblogs.com/LoganChen/p/11553388.html
Copyright © 2011-2022 走看看