class Topic(object):
"""主题类。保存所有观察者实例的引用,每个主题都可以有很多观察者
可以增加和删除观察者"""
def __init__(self):
self.obs = []
def Attach(self, ob):
self.obs.append(ob)
def Detach(self, ob):
self.obs.remove(ob)
def Notify(self):
for ob in self.obs:
ob.Update()
class Observer(object):
"""抽象观察者类,收到主题的变更通知时,更新自己"""
def Update(self):
raise NotImplementedError()
class ConcreteTopic(object):
"""一个具体主题"""
def __init__(self):
self.state = None
def ChangeState(self, newState):
self.state = newState
self.Notify()
class ConcreteObserver(object):
"""一个具体监听类"""
def __init__(self, topic):
self.topic = topic
def Update(self):
print self.topic.state
def client():
topic = ConcreteTopic()
topic.Attach(ConcreteObserver(topic))
topic.ChangeState('New State')
class Strategy(object):
"""抽象算法类"""
def AlgorithmInterface(self):
raise NotImplementedError()
class ConcreteStrategyA(Strategy):
def AlgorithmInterface(self):
print '算法A'
class ConcreteStrategyB(Strategy):
def AlgorithmInterface(self):
print '算法B'
class Context(object):
"""上下文,作用就是封装策略的实现细节,用户只需要知道有哪些策略可用"""
def __init__(self, strategy):
# 初始化时传入具体的策略实例
self.strategy = strategy
def ContextInterface(self):
# 负责调用具体的策略实例的接口
self.strategy.AlgorithmInterface()
def client(cond):
# 策略模式的使用演示
# 用户只需要根据不同的条件,将具体的算法实现类传递给Context,
# 然后调用Context暴露给用户的接口就行了。
if cond == 'A':
context = Context(ConcreteStrategyA())
elif cond == 'B':
context = Context(ConcreteStrategyB())
result = context.ContextInterface()
class Context(object):
def __init__(self, cond):
if cond == 'A':
self.strategy = Context(ConcreteStrategyA())
elif cond == 'B':
self.strategy = Context(ConcreteStrategyB())
def ContextInterface(self):
self.strategy.AlgorithmInterface()
def client(cond):
context = Context(cond)
result = context.ContextInterface()
机械节能产品生产企业官网模板...
大气智能家居家具装修装饰类企业通用网站模板...
礼品公司网站模板
宽屏简约大气婚纱摄影影楼模板...
蓝白WAP手机综合医院类整站源码(独立后台)...苏ICP备2024110244号-2 苏公网安备32050702011978号 增值电信业务经营许可证编号:苏B2-20251499 | Copyright 2018 - 2025 源码网商城 (www.ymwmall.com) 版权所有