过年在家瞎折腾,闲着无聊看到设计模式,于是就想着用Python实现一下。
简单工厂
根据传入的参数决定创建出哪一种产品类的实例。
class CashFactory:def createCashAdapter(self, type):if type == "满100减20":return CashReturn(100, 20)elif type == "打八折":return CashRebate(0.8)else:return CashNormal()class CashSuper(object):def __init__(self):pass@abstractmethoddef acceptCash(self, money):passclass CashNormal(CashSuper):def acceptCash(self, money):return moneyclass CashRebate(CashSuper):rebate = 1def __init__(self, rebate):self.rebate = rebatesuper().__init__()def acceptCash(self, money):return self.rebate * moneyclass CashReturn(CashSuper):moneyCondition = 0moneyReturn = 0def __init__(self, moneyCondition, moneyReturn):self.moneyCondition = moneyConditionself.moneyReturn = moneyReturnsuper().__init__()def acceptCash(self, money):ret = moneyif money >= self.moneyCondition:ret = money - math.floor(money / self.moneyCondition) * self.moneyReturnreturn ret# 调用工厂cashFactory = CashFactory()cashSuper = cashFactory.createCashAdapter(comboValue.get())result = cashSuper.acceptCash(money)
策略模式
定义一系列算法,所有算法完成相同的工作,实现不同,减少算法间的耦合,由Context确定具体算法,侧重算法的封装。
# contextclass CashContext:cashSuper = Nonedef __init__(self, type):if type == "满100减20":self.cashSuper = CashReturn(100, 20)elif type == "打八折":self.cashSuper = CashRebate(0.8)else:self.cashSuper = CashNormal()def getResult(self, money):return self.cashSuper.acceptCash(money)# 调用contextcashContext = CashContext(comboValue.get())result = cashContext.getResult(money)
代理模式
为其他对象提供一种代理以控制这个对象的访问
# 被代理类class RealSubject(Subject):def request(self):print('调用实际方法')# 代理类class Proxy(Subject):def __init__(self):super().__init__()self.realSubject = RealSubject()def request(self):self.preRequest()self.realSubject.request()self.postRequest()def preRequest(self):print("调用方法之前")def postRequest(self):print("调用方法之后")
原型模式
用原型实例指定创建对象的种类,并且通过拷贝这些原型创建对象。
# 使用Python的copy包来实现深拷贝和浅拷贝class Prototype(object):def __init__(self):print('创建成功')def clone(self):clone = copy.deepcopy(self)return clonep1 = Prototype()p2 = p1.clone()
模板方法模式
某一细节上的一系列过程或者一系列步骤,在个别步骤上实现不同时考虑模板方法。
# 抽象类,包含骨架和组成步骤class AbstractClass(object):def template_method(self):self.specific_method()self.abstract_method()def specific_method(self):print("调用方法")@abstractmethoddef abstract_method(self):raise ValueError('请实现方法')# 具体方法class ConcreteClass(AbstractClass):def abstract_method(self):print("Abstract实现")# 调用tm = ConcreteClass()tm.template_method()
装饰模式
动态给一个对象添加一些额外的职责。
# 抽象接口class Component(object):@abstractmethoddef operation(self):raise ValueError('请实现方法')# 装饰抽象类class Decorator(object):def __init__(self, component):self.component = componentdef operation(self):self.component.operation()class ConcreteDecorator(Decorator):def __init__(self, component):Decorator.__init__(self, component)def operation(self):Decorator.operation(self)self.addedFunction()def addedFunction(self):print('addedFunction')class ConcreteComponent(Component):def __init__(self):print('创建具体构建对象')def operation(self):print('调用构建对象方法')p = ConcreteComponent()p.operation()print('---')d = ConcreteDecorator(p)d.operation()
外观模式
为子系统中的一组接口提供一个一致的界面,此模式定义了一个高层接口。
# 外观类class Facade(object):def __init__(self):self.sys1 = Subsystem001()self.sys2 = Subsystem002()self.sys3 = Subsystem003()def method(self):self.sys1.method()self.sys2.method()self.sys3.method()class Subsystem001(object):def method(self):print('子系统1调用')class Subsystem002(object):def method(self):print('子系统2调用')class Subsystem003(object):def method(self):print('子系统3调用')facade = Facade()facade.method()
观察者模式
定义对象间的一种一对多的依赖关系,当一个对象的状态发生改变时,所有依赖于它的对象都得到通知并被自动更新。
class Observer(object):@abstractmethoddef response(self):passclass Subject(object):def __init__(self):self.observers = []def add_observer(self, observer):self.observers.append(observer)def remove_observer(self, observer):self.observers.remove(observer)@abstractmethoddef notify_observers(self):passclass ConcreteSubject(Subject):def notify_observers(self):print('观察目标改变')print('----------')for observer in self.observers:observer.response()class ConcreteObserver1(Observer):def response(self):print('观察者1变化')class ConcreteObserver2(Observer):def response(self):print('观察者2变化')subject = ConcreteSubject()obs1 = ConcreteObserver1()obs2 = ConcreteObserver2()subject.add_observer(obs1)subject.add_observer(obs2)subject.notify_observers()
状态模式
当对象状态改变时允许改变其行为,这个对象看起来像是改变了其类。解决当控制一个对象状态转换的条件表达式过于复杂时,把状态的判断逻辑转移到表示不同状态的一系列的类中。
class State:@abstractmethoddef handle(self):raise ValueError('请实现方法')class ConcreteState(State):def handle(self, context):print('当前状态A')context.setState(ConcreteState2())class ConcreteState2(State):def handle(self, context):print('当前状态B')context.setState(ConcreteState3())class Context(object):def __init__(self):self.state = ConcreteState()def setState(self, state):self.state = statedef getState(self):return self.statedef handle(self):self.state.handle(self)context = Context()context.handle()context.handle()
适配器模式
将一个类的接口转换成客户希望的另一种接口
class Target(object):@abstractmethoddef request(self):passclass Adapter:def __init__(self):passdef specificRequest(self):print('适配者业务被调用')class ClassAdapter(Adapter):def request(self):self.specificRequest()classAdapter = ClassAdapter()classAdapter.request()
桥接模式
将抽象部分与它的实现部分分离,是他们都可以独立地变化
class Abstract(object):def __init__(self, imple):self.imple = imple@abstractmethoddef operation(self):passclass RefinedAbstraction(Abstract):def __init__(self,imple):super(RefinedAbstraction,self).__init__(imple)def operation(self):print('扩展抽象角色被访问')self.imple.opreationImpl()class Implementor(object):@abstractmethoddef opreationImpl(self):passclass ConcreteImplementor(Implementor):def opreationImpl(self):print('实现类角色被访问')imple = ConcreteImplementor()abs = RefinedAbstraction(imple)abs.operation()
命令模式
将一个请求封装成一个对象,从而使你可以用不同的请求对客户进行参数化。
class Command(object):@abstractmethoddef execute(self):raise ValueError('请实现方法')class ConcreateCommand(Command):def __init__(self):self.receiver = Receiver()def execute(self):self.receiver.action()class Invoker(object):def __init__(self, command):self.command = commanddef call(self):print('调用者执行命令')self.command.execute()class Receiver:def action(self):print('接收者执行命令')cmd = ConcreateCommand()ir = Invoker(cmd)print('客户端发送命令开始')ir.call()
责任链模式
如果有多个对象有机会处理请求,责任链可使请求的发送者和接受者解耦,请求沿着责任链传递,直到有一个对象处理了它为止。
class Handler(object):def __init__(self):self.next = Nonedef setNext(self, next):self.next = nextdef getNext(self):return self.next@abstractmethoddef handleRequest(self, request):raise ValueError('请实现方法')class ConcreteHandler1(Handler):def handleRequest(self, request):if request == "one":print('处理者1处理')else:if self.getNext() is not None:self.getNext().handleRequest(request)else:print('处理完成')class ConcreteHandler2(Handler):def handleRequest(self, request):if request == "two":print('处理者2处理')else:if self.getNext() is not None:self.getNext().handleRequest(request)else:print('处理完成')handler1 = ConcreteHandler1()handler2 = ConcreteHandler2()handler1.setNext(handler2)handler1.handleRequest("two")
中介者模式
定义一个中介对象来封装一系列对象之间的交互,使原有对象之间的耦合松散,且可以独立地改变它们之间的交互
class Mediator(object):@abstractmethoddef register(self, colleague):raise ValueError('请实现方法')@abstractmethoddef relay(self, colleague):raise ValueError('请实现方法')class ConcreteMediator(Mediator):colleagues = []def register(self, colleague):if not self.colleagues.__contains__(colleague):self.colleagues.append(colleague)colleague.set_mediator(self)def relay(self, colleague):for ob in self.colleagues:if ob != colleague:ob.receive()class ConcreteColleague1(Colleague):def receive(self):print("具体类收到请求1")def send(self):print('具体类发送请求1')self.mediator.relay(self)class ConcreteColleague2(Colleague):def receive(self):print("具体类收到请求2")def send(self):print('具体类发送请求2')self.mediator.relay(self)class Colleague(object):def __init__(self):self.mediator = Nonedef set_mediator(self, mediator):self.mediator = mediatordef get_mediator(self):return self.mediator@abstractmethoddef receive(self):raise ValueError('请实现方法')@abstractmethoddef send(self):raise ValueError('请实现方法')md = ConcreteMediator()c1 = ConcreteColleague1()c2 = ConcreteColleague2()md.register(c1)md.register(c2)c1.send()print('----------------')c2.send()
享元模式
通过共享的方式高效的支持大量细粒度的对象。
class Flyweight:@abstractmethoddef operation(self, unshared):passclass ConcreteFlyweight(Flyweight):def __init__(self, key):self.key = keyprint('享元' + key + '被创建')def operation(self, unshared):print('享元' + self.key)print('非享元' + unshared.get_info())class FlyweightFactory(object):_flyweights = {}def get_flyweight(self, key):if not self._flyweights.get(key):self._flyweights[key] = ConcreteFlyweight(key)return self._flyweights[key]class UnsharedConcreteFlyweight:def __init__(self, info):self.info = infodef get_info(self):return self.infodef set_info(self, info):self.info = infofactory = FlyweightFactory()f01 = factory.get_flyweight('a')f02 = factory.get_flyweight('a')f03 = factory.get_flyweight('b')f04 = factory.get_flyweight('b')f01.operation(UnsharedConcreteFlyweight('第1次调用a'))f01.operation(UnsharedConcreteFlyweight('第2次调用a'))
访问者模式
将作用于某种数据结构中的各元素的操作分离出来封装成独立的类,使其在不改变数据结构的前提下可以添加作用于这些元素的新的操作,为数据结构中的每个元素提供多种访问方式。它将对数据的操作与数据结构进行分离。
class Memento(object):def __init__(self, state):self._state = statedef setState(self, state):self._state = statedef getState(self):return self._stateclass Caretaker:def __init__(self):self._memento = Nonedef setMemento(self, memento):self._memento = mementodef getMemento(self):return self._mementoclass Originator:def __init__(self):self._state = Nonedef setState(self, state):self._state = statedef getState(self):return self._statedef createMemento(self):return Memento(self._state)def restoreMemento(self, memento):self.setState(memento.getState())
完整代码点击这里码云