解释器模式
多用于DSL,领域专用语言,
from pyparsing import Word, OneOrMore, Optional, Group, Suppress, alphanums word = Word(alphanums) command = Group(OneOrMore(word)) token = Suppress("->") device = Group(OneOrMore(word)) argument = Group(OneOrMore(word)) event = command + token + device + Optional(token + argument)
上面的event可以用
event.parseString(t)
解析出t
'open -> gate' 或者
'increase -> boiler temperature -> 5 degrees'
并从中提取出open,gate用于自定义的操作。
观察者模式
一个对象的属性的改变可以同时通知观察者,定义观察者HexFormatter
class HexFormatter: def notify(self, publisher): print("{}: '{}' has now hex data = {}".format(type(self).__name__, publisher.name, hex(publisher.data)))
观察对象
class Publisher: def __init__(self): self.observers = [] #添加观察者 def add(self, observer): if observer not in self.observers: self.observers.append(observer) else: print('Failed to add: {}'.format(observer)) def remove(self, observer): try: self.observers.remove(observer) except ValueError: print('Failed to remove: {}'.format(observer)) def notify(self): [o.notify(self) for o in self.observers] class DefaultFormatter(Publisher): def __init__(self, name): Publisher.__init__(self) self.name = name self._data = 0 def __str__(self): return "{}: '{}' has data = {}".format(type(self).__name__, self.name, self._data) #以object.data方式访问变量 @property def data(self): return self._data #改变data值,最后通知观察者 @data.setter def data(self, new_value): try: self._data = int(new_value) except ValueError as e: print('Error: {}'.format(e)) else: self.notify()
适配器模式
class Adapter: def __init__(self,obj,adapter_method): self.obj = obj #add obj attr #var = vars(obj) #self.__dict__.update(var) self.__dict__.update(adapter_method) def __str__(self): return str(self.obj)