软件设计模式汇总

点击这里查看软件设计模式,非常详细(Java实现)
以下使用python实现的,应该掌握单例模式、工厂模式、观察者模式。

1 单例模式

# 改写__new__的模式
class Singleton(object):
    def __init__(self, name):
        self.name = name
    def __new__(cls, *args, **kwargs):
        """必须有返回值"""
        if not hasattr(cls, '_instance'):
            cls._instance = super(Singleton, cls).__new__(cls)
        return cls._instance

def singleton(cls):
    instance = {}

    def check(*args, **kwargs):
        if cls not in instance:
            instance[cls] = cls(*args, **kwargs)
        # print(instance)
        return instance[cls]
    return check

# 装饰器形式的单例模式
@singleton
class Singleton2(object):
    def __init__(self, name):
        self.name = name

if __name__ == '__main__': 
    # 第一种方式输出最后的name,第二种方式输出第一个实例的name
    s = Singleton2('wgj')
    print(s.name)
    s2 = Singleton2('yq')
    print(s2.name)
    print(s.name)

2 工厂模式

class Shoe(object):
    """鞋,基类(抽象产品类)"""
    def walk(self):
        pass

class LeatherShoe(Shoe):
    """皮鞋(具体产品类)"""
    def walk(self):
        print("我是皮鞋!")

class SoccerShoe(Shoe):
    """球鞋(具体产品类)"""
    def walk(self):
        print("我是球鞋!")

class ShoeFactory(object):
    """鞋厂,基类(抽象工厂)"""
    def make(self):
        pass

class LeatherShoeFactory(ShoeFactory):
    """皮鞋工厂(具体工厂)"""
    def make(self):
        return LeatherShoe()

class SoccerShoeFactory(ShoeFactory):
    """球鞋工厂(具体工厂)"""
    def make(self):
        return SoccerShoe()
        
if __name__ == '__main__':
    factory = LeatherShoeFactory()
    shoe = factory.make()
    shoe.walk()

猜你喜欢

转载自blog.csdn.net/qq_35556064/article/details/82908471
今日推荐