├── README.md ├── Decorator.py ├── Singleton.py ├── Iterator.py ├── Interpreter.py ├── Proxy.py ├── Factory_Method.py ├── Visitor.py ├── Prototype.py ├── Command.py ├── Flyweight.py ├── Composite.py ├── Bridge.py ├── Chain.py ├── Strategy.py ├── Template_Method.py ├── facade.py ├── Builder.py ├── Abstract_Factory.py ├── State.py ├── Adapter.py ├── Observer.py ├── Memento.py ├── Mediator.py └── LICENSE /README.md: -------------------------------------------------------------------------------- 1 | # Design_pattern_of_python 2 | 以图文形式介绍了二十三种常见设计模式,并使用python进行实现 -------------------------------------------------------------------------------- /Decorator.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | #coding:utf8 3 | ''' 4 | Decorator 5 | ''' 6 | 7 | class foo(object): 8 | def f1(self): 9 | print("original f1") 10 | 11 | def f2(self): 12 | print("original f2") 13 | 14 | 15 | class foo_decorator(object): 16 | def __init__(self, decoratee): 17 | self._decoratee = decoratee 18 | 19 | def f1(self): 20 | print("decorated f1") 21 | self._decoratee.f1() 22 | 23 | def __getattr__(self, name): 24 | return getattr(self._decoratee, name) 25 | 26 | u = foo() 27 | v = foo_decorator(u) 28 | v.f1() 29 | v.f2() 30 | -------------------------------------------------------------------------------- /Singleton.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | #coding:utf8 3 | ''' 4 | Singleton 5 | ''' 6 | 7 | class Singleton(object): 8 | ''''' A python style singleton ''' 9 | 10 | def __new__(cls, *args, **kw): 11 | if not hasattr(cls, '_instance'): 12 | org = super(Singleton, cls) 13 | cls._instance = org.__new__(cls, *args, **kw) 14 | return cls._instance 15 | 16 | 17 | if __name__ == '__main__': 18 | class SingleSpam(Singleton): 19 | def __init__(self, s): 20 | self.s = s 21 | 22 | def __str__(self): 23 | return self.s 24 | 25 | 26 | s1 = SingleSpam('spam') 27 | print id(s1), s1 28 | s2 = SingleSpam('spa') 29 | print id(s2), s2 30 | print id(s1), s1 -------------------------------------------------------------------------------- /Iterator.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | #coding:utf8 3 | ''' 4 | Interator 5 | ''' 6 | def count_to(count): 7 | """Counts by word numbers, up to a maximum of five""" 8 | numbers = ["one", "two", "three", "four", "five"] 9 | # enumerate() returns a tuple containing a count (from start which 10 | # defaults to 0) and the values obtained from iterating over sequence 11 | for pos, number in zip(range(count), numbers): 12 | yield number 13 | 14 | # Test the generator 15 | count_to_two = lambda: count_to(2) 16 | count_to_five = lambda: count_to(5) 17 | 18 | print('Counting to two...') 19 | for number in count_to_two(): 20 | print number 21 | 22 | print " " 23 | 24 | print('Counting to five...') 25 | for number in count_to_five(): 26 | print number 27 | 28 | print " " 29 | -------------------------------------------------------------------------------- /Interpreter.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | #coding:utf8 3 | ''' 4 | Interpreter 5 | ''' 6 | 7 | class Context: 8 | def __init__(self): 9 | self.input="" 10 | self.output="" 11 | 12 | class AbstractExpression: 13 | def Interpret(self,context): 14 | pass 15 | 16 | class Expression(AbstractExpression): 17 | def Interpret(self,context): 18 | print "terminal interpret" 19 | 20 | class NonterminalExpression(AbstractExpression): 21 | def Interpret(self,context): 22 | print "Nonterminal interpret" 23 | 24 | if __name__ == "__main__": 25 | context= "" 26 | c = [] 27 | c = c + [Expression()] 28 | c = c + [NonterminalExpression()] 29 | c = c + [Expression()] 30 | c = c + [Expression()] 31 | for a in c: 32 | a.Interpret(context) -------------------------------------------------------------------------------- /Proxy.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | #coding:utf8 3 | ''' 4 | Proxy 5 | ''' 6 | 7 | import time 8 | 9 | class SalesManager: 10 | def work(self): 11 | print("Sales Manager working...") 12 | 13 | def talk(self): 14 | print("Sales Manager ready to talk") 15 | 16 | class Proxy: 17 | def __init__(self): 18 | self.busy = 'No' 19 | self.sales = None 20 | 21 | def work(self): 22 | print("Proxy checking for Sales Manager availability") 23 | if self.busy == 'No': 24 | self.sales = SalesManager() 25 | time.sleep(2) 26 | self.sales.talk() 27 | else: 28 | time.sleep(2) 29 | print("Sales Manager is busy") 30 | 31 | 32 | if __name__ == '__main__': 33 | p = Proxy() 34 | p.work() 35 | p.busy = 'Yes' 36 | p.work() 37 | -------------------------------------------------------------------------------- /Factory_Method.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | #coding:utf8 3 | ''' 4 | Factory Method 5 | ''' 6 | 7 | class ChinaGetter: 8 | """A simple localizer a la gettext""" 9 | def __init__(self): 10 | self.trans = dict(dog="小狗", cat="小猫") 11 | 12 | def get(self, msgid): 13 | """We'll punt if we don't have a translation""" 14 | try: 15 | return self.trans[msgid] 16 | except KeyError: 17 | return str(msgid) 18 | 19 | 20 | class EnglishGetter: 21 | """Simply echoes the msg ids""" 22 | def get(self, msgid): 23 | return str(msgid) 24 | 25 | 26 | def get_localizer(language="English"): 27 | """The factory method""" 28 | languages = dict(English=EnglishGetter, China=ChinaGetter) 29 | return languages[language]() 30 | 31 | # Create our localizers 32 | e, g = get_localizer("English"), get_localizer("China") 33 | # Localize some text 34 | for msgid in "dog parrot cat bear".split(): 35 | print(e.get(msgid), g.get(msgid)) 36 | -------------------------------------------------------------------------------- /Visitor.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | #coding:utf8 3 | ''' 4 | Visitor 5 | ''' 6 | class Node(object): 7 | pass 8 | 9 | class A(Node): 10 | pass 11 | 12 | class B(Node): 13 | pass 14 | 15 | class C(A, B): 16 | pass 17 | 18 | class Visitor(object): 19 | def visit(self, node, *args, **kwargs): 20 | meth = None 21 | for cls in node.__class__.__mro__: 22 | meth_name = 'visit_'+cls.__name__ 23 | meth = getattr(self, meth_name, None) 24 | if meth: 25 | break 26 | 27 | if not meth: 28 | meth = self.generic_visit 29 | return meth(node, *args, **kwargs) 30 | 31 | def generic_visit(self, node, *args, **kwargs): 32 | print('generic_visit '+node.__class__.__name__) 33 | 34 | def visit_B(self, node, *args, **kwargs): 35 | print('visit_B '+node.__class__.__name__) 36 | 37 | a = A() 38 | b = B() 39 | c = C() 40 | visitor = Visitor() 41 | visitor.visit(a) 42 | visitor.visit(b) 43 | visitor.visit(c) 44 | -------------------------------------------------------------------------------- /Prototype.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | #coding:utf8 3 | ''' 4 | Prototype 5 | ''' 6 | 7 | import copy 8 | 9 | class Prototype: 10 | def __init__(self): 11 | self._objects = {} 12 | 13 | def register_object(self, name, obj): 14 | """Register an object""" 15 | self._objects[name] = obj 16 | 17 | def unregister_object(self, name): 18 | """Unregister an object""" 19 | del self._objects[name] 20 | 21 | def clone(self, name, **attr): 22 | """Clone a registered object and update inner attributes dictionary""" 23 | obj = copy.deepcopy(self._objects.get(name)) 24 | obj.__dict__.update(attr) 25 | return obj 26 | 27 | 28 | def main(): 29 | class A: 30 | def __str__(self): 31 | return "I am A" 32 | 33 | a = A() 34 | prototype = Prototype() 35 | prototype.register_object('a', a) 36 | b = prototype.clone('a', a=1, b=2, c=3) 37 | 38 | print(a) 39 | print(b.a, b.b, b.c) 40 | 41 | 42 | if __name__ == '__main__': 43 | main() 44 | -------------------------------------------------------------------------------- /Command.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | #coding:utf8 3 | 4 | """ 5 | Command 6 | """ 7 | import os 8 | 9 | class MoveFileCommand(object): 10 | def __init__(self, src, dest): 11 | self.src = src 12 | self.dest = dest 13 | 14 | def execute(self): 15 | self() 16 | 17 | def __call__(self): 18 | print('renaming {} to {}'.format(self.src, self.dest)) 19 | os.rename(self.src, self.dest) 20 | 21 | def undo(self): 22 | print('renaming {} to {}'.format(self.dest, self.src)) 23 | os.rename(self.dest, self.src) 24 | 25 | 26 | if __name__ == "__main__": 27 | command_stack = [] 28 | 29 | # commands are just pushed into the command stack 30 | command_stack.append(MoveFileCommand('foo.txt', 'bar.txt')) 31 | command_stack.append(MoveFileCommand('bar.txt', 'baz.txt')) 32 | 33 | # they can be executed later on 34 | for cmd in command_stack: 35 | cmd.execute() 36 | 37 | # and can also be undone at will 38 | for cmd in reversed(command_stack): 39 | cmd.undo() 40 | -------------------------------------------------------------------------------- /Flyweight.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | #coding:utf8 3 | ''' 4 | Flyweight 5 | ''' 6 | 7 | import weakref 8 | 9 | 10 | class Card(object): 11 | """The object pool. Has builtin reference counting""" 12 | _CardPool = weakref.WeakValueDictionary() 13 | 14 | """Flyweight implementation. If the object exists in the 15 | pool just return it (instead of creating a new one)""" 16 | def __new__(cls, value, suit): 17 | obj = Card._CardPool.get(value + suit, None) 18 | if not obj: 19 | obj = object.__new__(cls) 20 | Card._CardPool[value + suit] = obj 21 | obj.value, obj.suit = value, suit 22 | return obj 23 | 24 | # def __init__(self, value, suit): 25 | # self.value, self.suit = value, suit 26 | 27 | def __repr__(self): 28 | return "" % (self.value, self.suit) 29 | 30 | 31 | if __name__ == '__main__': 32 | # comment __new__ and uncomment __init__ to see the difference 33 | c1 = Card('9', 'h') 34 | c2 = Card('9', 'h') 35 | print(c1, c2) 36 | print(c1 == c2) 37 | print(id(c1), id(c2)) 38 | -------------------------------------------------------------------------------- /Composite.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | #coding:utf8 3 | 4 | """ 5 | Composite 6 | """ 7 | 8 | class Component: 9 | def __init__(self,strName): 10 | self.m_strName = strName 11 | def Add(self,com): 12 | pass 13 | def Display(self,nDepth): 14 | pass 15 | 16 | class Leaf(Component): 17 | def Add(self,com): 18 | print "leaf can't add" 19 | def Display(self,nDepth): 20 | strtemp = "-" * nDepth 21 | strtemp=strtemp+self.m_strName 22 | print strtemp 23 | 24 | class Composite(Component): 25 | def __init__(self,strName): 26 | self.m_strName = strName 27 | self.c = [] 28 | def Add(self,com): 29 | self.c.append(com) 30 | def Display(self,nDepth): 31 | strtemp = "-"*nDepth 32 | strtemp=strtemp+self.m_strName 33 | print strtemp 34 | for com in self.c: 35 | com.Display(nDepth+2) 36 | 37 | if __name__ == "__main__": 38 | p = Composite("Wong") 39 | p.Add(Leaf("Lee")) 40 | p.Add(Leaf("Zhao")) 41 | p1 = Composite("Wu") 42 | p1.Add(Leaf("San")) 43 | p.Add(p1) 44 | p.Display(1); -------------------------------------------------------------------------------- /Bridge.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | #coding:utf8 3 | ''' 4 | Bridge 5 | ''' 6 | 7 | 8 | # ConcreteImplementor 1/2 9 | class DrawingAPI1(object): 10 | def draw_circle(self, x, y, radius): 11 | print('API1.circle at {}:{} radius {}'.format(x, y, radius)) 12 | 13 | 14 | # ConcreteImplementor 2/2 15 | class DrawingAPI2(object): 16 | def draw_circle(self, x, y, radius): 17 | print('API2.circle at {}:{} radius {}'.format(x, y, radius)) 18 | 19 | 20 | # Refined Abstraction 21 | class CircleShape(object): 22 | def __init__(self, x, y, radius, drawing_api): 23 | self._x = x 24 | self._y = y 25 | self._radius = radius 26 | self._drawing_api = drawing_api 27 | 28 | # low-level i.e. Implementation specific 29 | def draw(self): 30 | self._drawing_api.draw_circle(self._x, self._y, self._radius) 31 | 32 | # high-level i.e. Abstraction specific 33 | def scale(self, pct): 34 | self._radius *= pct 35 | 36 | 37 | def main(): 38 | shapes = ( 39 | CircleShape(1, 2, 3, DrawingAPI1()), 40 | CircleShape(5, 7, 11, DrawingAPI2()) 41 | ) 42 | 43 | for shape in shapes: 44 | shape.scale(2.5) 45 | shape.draw() 46 | 47 | 48 | if __name__ == '__main__': 49 | main() 50 | -------------------------------------------------------------------------------- /Chain.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | #coding:utf8 3 | 4 | """ 5 | Chain 6 | """ 7 | class Handler: 8 | def successor(self, successor): 9 | self.successor = successor 10 | 11 | class ConcreteHandler1(Handler): 12 | def handle(self, request): 13 | if request > 0 and request <= 10: 14 | print("in handler1") 15 | else: 16 | self.successor.handle(request) 17 | 18 | class ConcreteHandler2(Handler): 19 | def handle(self, request): 20 | if request > 10 and request <= 20: 21 | print("in handler2") 22 | else: 23 | self.successor.handle(request) 24 | 25 | class ConcreteHandler3(Handler): 26 | def handle(self, request): 27 | if request > 20 and request <= 30: 28 | print("in handler3") 29 | else: 30 | print('end of chain, no handler for {}'.format(request)) 31 | 32 | class Client: 33 | def __init__(self): 34 | h1 = ConcreteHandler1() 35 | h2 = ConcreteHandler2() 36 | h3 = ConcreteHandler3() 37 | 38 | h1.successor(h2) 39 | h2.successor(h3) 40 | 41 | requests = [2, 5, 14, 22, 18, 3, 35, 27, 20] 42 | for request in requests: 43 | h1.handle(request) 44 | 45 | if __name__ == "__main__": 46 | client = Client() 47 | -------------------------------------------------------------------------------- /Strategy.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | #coding:utf8 3 | """ 4 | Strategy 5 | In most of other languages Strategy pattern is implemented via creating some base strategy interface/abstract class and 6 | subclassing it with a number of concrete strategies (as we can see at http://en.wikipedia.org/wiki/Strategy_pattern), 7 | however Python supports higher-order functions and allows us to have only one class and inject functions into it's 8 | instances, as shown in this example. 9 | """ 10 | import types 11 | 12 | 13 | class StrategyExample: 14 | def __init__(self, func=None): 15 | self.name = 'Strategy Example 0' 16 | if func is not None: 17 | self.execute = types.MethodType(func, self) 18 | 19 | def execute(self): 20 | print(self.name) 21 | 22 | def execute_replacement1(self): 23 | print(self.name + ' from execute 1') 24 | 25 | def execute_replacement2(self): 26 | print(self.name + ' from execute 2') 27 | 28 | if __name__ == '__main__': 29 | strat0 = StrategyExample() 30 | 31 | strat1 = StrategyExample(execute_replacement1) 32 | strat1.name = 'Strategy Example 1' 33 | 34 | strat2 = StrategyExample(execute_replacement2) 35 | strat2.name = 'Strategy Example 2' 36 | 37 | strat0.execute() 38 | strat1.execute() 39 | strat2.execute() 40 | -------------------------------------------------------------------------------- /Template_Method.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | #coding:utf8 3 | ''' 4 | Template Method 5 | ''' 6 | 7 | ingredients = "spam eggs apple" 8 | line = '-' * 10 9 | 10 | # Skeletons 11 | def iter_elements(getter, action): 12 | """Template skeleton that iterates items""" 13 | for element in getter(): 14 | action(element) 15 | print(line) 16 | 17 | def rev_elements(getter, action): 18 | """Template skeleton that iterates items in reverse order""" 19 | for element in getter()[::-1]: 20 | action(element) 21 | print(line) 22 | 23 | # Getters 24 | def get_list(): 25 | return ingredients.split() 26 | 27 | def get_lists(): 28 | return [list(x) for x in ingredients.split()] 29 | 30 | # Actions 31 | def print_item(item): 32 | print(item) 33 | 34 | def reverse_item(item): 35 | print(item[::-1]) 36 | 37 | # Makes templates 38 | def make_template(skeleton, getter, action): 39 | """Instantiate a template method with getter and action""" 40 | def template(): 41 | skeleton(getter, action) 42 | return template 43 | 44 | # Create our template functions 45 | templates = [make_template(s, g, a) 46 | for g in (get_list, get_lists) 47 | for a in (print_item, reverse_item) 48 | for s in (iter_elements, rev_elements)] 49 | 50 | # Execute them 51 | for template in templates: 52 | template() 53 | -------------------------------------------------------------------------------- /facade.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | #coding:utf8 3 | ''' 4 | Facade 5 | ''' 6 | import time 7 | 8 | SLEEP = 0.5 9 | 10 | # Complex Parts 11 | class TC1: 12 | def run(self): 13 | print("###### In Test 1 ######") 14 | time.sleep(SLEEP) 15 | print("Setting up") 16 | time.sleep(SLEEP) 17 | print("Running test") 18 | time.sleep(SLEEP) 19 | print("Tearing down") 20 | time.sleep(SLEEP) 21 | print("Test Finished\n") 22 | 23 | 24 | class TC2: 25 | def run(self): 26 | print("###### In Test 2 ######") 27 | time.sleep(SLEEP) 28 | print("Setting up") 29 | time.sleep(SLEEP) 30 | print("Running test") 31 | time.sleep(SLEEP) 32 | print("Tearing down") 33 | time.sleep(SLEEP) 34 | print("Test Finished\n") 35 | 36 | 37 | class TC3: 38 | def run(self): 39 | print("###### In Test 3 ######") 40 | time.sleep(SLEEP) 41 | print("Setting up") 42 | time.sleep(SLEEP) 43 | print("Running test") 44 | time.sleep(SLEEP) 45 | print("Tearing down") 46 | time.sleep(SLEEP) 47 | print("Test Finished\n") 48 | 49 | 50 | # Facade 51 | class TestRunner: 52 | def __init__(self): 53 | self.tc1 = TC1() 54 | self.tc2 = TC2() 55 | self.tc3 = TC3() 56 | self.tests = [i for i in (self.tc1, self.tc2, self.tc3)] 57 | 58 | def runAll(self): 59 | [i.run() for i in self.tests] 60 | 61 | 62 | # Client 63 | if __name__ == '__main__': 64 | testrunner = TestRunner() 65 | testrunner.runAll() 66 | -------------------------------------------------------------------------------- /Builder.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | #coding:utf8 3 | 4 | """ 5 | Builder 6 | """ 7 | 8 | # Director 9 | class Director(object): 10 | def __init__(self): 11 | self.builder = None 12 | 13 | def construct_building(self): 14 | self.builder.new_building() 15 | self.builder.build_floor() 16 | self.builder.build_size() 17 | 18 | def get_building(self): 19 | return self.builder.building 20 | 21 | 22 | # Abstract Builder 23 | class Builder(object): 24 | def __init__(self): 25 | self.building = None 26 | 27 | def new_building(self): 28 | self.building = Building() 29 | 30 | 31 | # Concrete Builder 32 | class BuilderHouse(Builder): 33 | def build_floor(self): 34 | self.building.floor = 'One' 35 | 36 | def build_size(self): 37 | self.building.size = 'Big' 38 | 39 | 40 | class BuilderFlat(Builder): 41 | def build_floor(self): 42 | self.building.floor = 'More than One' 43 | 44 | def build_size(self): 45 | self.building.size = 'Small' 46 | 47 | 48 | # Product 49 | class Building(object): 50 | def __init__(self): 51 | self.floor = None 52 | self.size = None 53 | 54 | def __repr__(self): 55 | return 'Floor: %s | Size: %s' % (self.floor, self.size) 56 | 57 | 58 | # Client 59 | if __name__ == "__main__": 60 | director = Director() 61 | director.builder = BuilderHouse() 62 | director.construct_building() 63 | building = director.get_building() 64 | print(building) 65 | director.builder = BuilderFlat() 66 | director.construct_building() 67 | building = director.get_building() 68 | print(building) 69 | -------------------------------------------------------------------------------- /Abstract_Factory.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | #coding:utf8 3 | ''' 4 | Abstract Factory 5 | ''' 6 | 7 | import random 8 | 9 | class PetShop: 10 | """A pet shop""" 11 | 12 | def __init__(self, animal_factory=None): 13 | """pet_factory is our abstract factory. 14 | We can set it at will.""" 15 | 16 | self.pet_factory = animal_factory 17 | 18 | def show_pet(self): 19 | """Creates and shows a pet using the 20 | abstract factory""" 21 | 22 | pet = self.pet_factory.get_pet() 23 | print("This is a lovely", str(pet)) 24 | print("It says", pet.speak()) 25 | print("It eats", self.pet_factory.get_food()) 26 | 27 | 28 | # Stuff that our factory makes 29 | 30 | class Dog: 31 | def speak(self): 32 | return "woof" 33 | 34 | def __str__(self): 35 | return "Dog" 36 | 37 | 38 | class Cat: 39 | def speak(self): 40 | return "meow" 41 | 42 | def __str__(self): 43 | return "Cat" 44 | 45 | 46 | # Factory classes 47 | 48 | class DogFactory: 49 | def get_pet(self): 50 | return Dog() 51 | 52 | def get_food(self): 53 | return "dog food" 54 | 55 | 56 | class CatFactory: 57 | def get_pet(self): 58 | return Cat() 59 | 60 | def get_food(self): 61 | return "cat food" 62 | 63 | 64 | # Create the proper family 65 | def get_factory(): 66 | """Let's be dynamic!""" 67 | return random.choice([DogFactory, CatFactory])() 68 | 69 | 70 | # Show pets with various factories 71 | if __name__ == "__main__": 72 | shop = PetShop() 73 | for i in range(3): 74 | shop.pet_factory = get_factory() 75 | shop.show_pet() 76 | print("=" * 20) -------------------------------------------------------------------------------- /State.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | #coding:utf8 3 | ''' 4 | State 5 | ''' 6 | 7 | class State(object): 8 | """Base state. This is to share functionality""" 9 | 10 | def scan(self): 11 | """Scan the dial to the next station""" 12 | self.pos += 1 13 | if self.pos == len(self.stations): 14 | self.pos = 0 15 | print("Scanning... Station is", self.stations[self.pos], self.name) 16 | 17 | 18 | class AmState(State): 19 | def __init__(self, radio): 20 | self.radio = radio 21 | self.stations = ["1250", "1380", "1510"] 22 | self.pos = 0 23 | self.name = "AM" 24 | 25 | def toggle_amfm(self): 26 | print("Switching to FM") 27 | self.radio.state = self.radio.fmstate 28 | 29 | class FmState(State): 30 | def __init__(self, radio): 31 | self.radio = radio 32 | self.stations = ["81.3", "89.1", "103.9"] 33 | self.pos = 0 34 | self.name = "FM" 35 | 36 | def toggle_amfm(self): 37 | print("Switching to AM") 38 | self.radio.state = self.radio.amstate 39 | 40 | class Radio(object): 41 | """A radio. It has a scan button, and an AM/FM toggle switch.""" 42 | def __init__(self): 43 | """We have an AM state and an FM state""" 44 | self.amstate = AmState(self) 45 | self.fmstate = FmState(self) 46 | self.state = self.amstate 47 | 48 | def toggle_amfm(self): 49 | self.state.toggle_amfm() 50 | 51 | def scan(self): 52 | self.state.scan() 53 | 54 | # Test our radio out 55 | if __name__ == '__main__': 56 | radio = Radio() 57 | actions = [radio.scan] * 2 + [radio.toggle_amfm] + [radio.scan] * 2 58 | actions = actions * 2 59 | 60 | for action in actions: 61 | action() 62 | -------------------------------------------------------------------------------- /Adapter.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | #coding:utf8 3 | ''' 4 | Adapter 5 | ''' 6 | 7 | import os 8 | 9 | 10 | class Dog(object): 11 | def __init__(self): 12 | self.name = "Dog" 13 | 14 | def bark(self): 15 | return "woof!" 16 | 17 | 18 | class Cat(object): 19 | def __init__(self): 20 | self.name = "Cat" 21 | 22 | def meow(self): 23 | return "meow!" 24 | 25 | 26 | class Human(object): 27 | def __init__(self): 28 | self.name = "Human" 29 | 30 | def speak(self): 31 | return "'hello'" 32 | 33 | 34 | class Car(object): 35 | def __init__(self): 36 | self.name = "Car" 37 | 38 | def make_noise(self, octane_level): 39 | return "vroom%s" % ("!" * octane_level) 40 | 41 | 42 | class Adapter(object): 43 | """ 44 | Adapts an object by replacing methods. 45 | Usage: 46 | dog = Dog 47 | dog = Adapter(dog, dict(make_noise=dog.bark)) 48 | """ 49 | def __init__(self, obj, adapted_methods): 50 | """We set the adapted methods in the object's dict""" 51 | self.obj = obj 52 | self.__dict__.update(adapted_methods) 53 | 54 | def __getattr__(self, attr): 55 | """All non-adapted calls are passed to the object""" 56 | return getattr(self.obj, attr) 57 | 58 | 59 | def main(): 60 | objects = [] 61 | dog = Dog() 62 | objects.append(Adapter(dog, dict(make_noise=dog.bark))) 63 | cat = Cat() 64 | objects.append(Adapter(cat, dict(make_noise=cat.meow))) 65 | human = Human() 66 | objects.append(Adapter(human, dict(make_noise=human.speak))) 67 | car = Car() 68 | car_noise = lambda: car.make_noise(3) 69 | objects.append(Adapter(car, dict(make_noise=car_noise))) 70 | 71 | for obj in objects: 72 | print "A", obj.name, "goes", obj.make_noise() 73 | 74 | 75 | if __name__ == "__main__": 76 | main() -------------------------------------------------------------------------------- /Observer.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | #coding:utf8 3 | ''' 4 | Observer 5 | ''' 6 | 7 | 8 | class Subject(object): 9 | def __init__(self): 10 | self._observers = [] 11 | 12 | def attach(self, observer): 13 | if not observer in self._observers: 14 | self._observers.append(observer) 15 | 16 | def detach(self, observer): 17 | try: 18 | self._observers.remove(observer) 19 | except ValueError: 20 | pass 21 | 22 | def notify(self, modifier=None): 23 | for observer in self._observers: 24 | if modifier != observer: 25 | observer.update(self) 26 | 27 | # Example usage 28 | class Data(Subject): 29 | def __init__(self, name=''): 30 | Subject.__init__(self) 31 | self.name = name 32 | self._data = 0 33 | 34 | @property 35 | def data(self): 36 | return self._data 37 | 38 | @data.setter 39 | def data(self, value): 40 | self._data = value 41 | self.notify() 42 | 43 | class HexViewer: 44 | def update(self, subject): 45 | print('HexViewer: Subject %s has data 0x%x' % 46 | (subject.name, subject.data)) 47 | 48 | class DecimalViewer: 49 | def update(self, subject): 50 | print('DecimalViewer: Subject %s has data %d' % 51 | (subject.name, subject.data)) 52 | 53 | # Example usage... 54 | def main(): 55 | data1 = Data('Data 1') 56 | data2 = Data('Data 2') 57 | view1 = DecimalViewer() 58 | view2 = HexViewer() 59 | data1.attach(view1) 60 | data1.attach(view2) 61 | data2.attach(view2) 62 | data2.attach(view1) 63 | 64 | print("Setting Data 1 = 10") 65 | data1.data = 10 66 | print("Setting Data 2 = 15") 67 | data2.data = 15 68 | print("Setting Data 1 = 3") 69 | data1.data = 3 70 | print("Setting Data 2 = 5") 71 | data2.data = 5 72 | print("Detach HexViewer from data1 and data2.") 73 | data1.detach(view2) 74 | data2.detach(view2) 75 | print("Setting Data 1 = 10") 76 | data1.data = 10 77 | print("Setting Data 2 = 15") 78 | data2.data = 15 79 | 80 | if __name__ == '__main__': 81 | main() 82 | -------------------------------------------------------------------------------- /Memento.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | #coding:utf8 3 | ''' 4 | Memento 5 | ''' 6 | 7 | import copy 8 | 9 | def Memento(obj, deep=False): 10 | state = (copy.copy, copy.deepcopy)[bool(deep)](obj.__dict__) 11 | 12 | def Restore(): 13 | obj.__dict__.clear() 14 | obj.__dict__.update(state) 15 | return Restore 16 | 17 | class Transaction: 18 | """A transaction guard. This is really just 19 | syntactic suggar arount a memento closure. 20 | """ 21 | deep = False 22 | 23 | def __init__(self, *targets): 24 | self.targets = targets 25 | self.Commit() 26 | 27 | def Commit(self): 28 | self.states = [Memento(target, self.deep) for target in self.targets] 29 | 30 | def Rollback(self): 31 | for st in self.states: 32 | st() 33 | 34 | class transactional(object): 35 | """Adds transactional semantics to methods. Methods decorated with 36 | @transactional will rollback to entry state upon exceptions. 37 | """ 38 | def __init__(self, method): 39 | self.method = method 40 | 41 | def __get__(self, obj, T): 42 | def transaction(*args, **kwargs): 43 | state = Memento(obj) 44 | try: 45 | return self.method(obj, *args, **kwargs) 46 | except: 47 | state() 48 | raise 49 | return transaction 50 | 51 | class NumObj(object): 52 | def __init__(self, value): 53 | self.value = value 54 | 55 | def __repr__(self): 56 | return '<%s: %r>' % (self.__class__.__name__, self.value) 57 | 58 | def Increment(self): 59 | self.value += 1 60 | 61 | @transactional 62 | def DoStuff(self): 63 | self.value = '1111' # <- invalid value 64 | self.Increment() # <- will fail and rollback 65 | 66 | if __name__ == '__main__': 67 | n = NumObj(-1) 68 | print(n) 69 | t = Transaction(n) 70 | try: 71 | for i in range(3): 72 | n.Increment() 73 | print(n) 74 | t.Commit() 75 | print('-- commited') 76 | for i in range(3): 77 | n.Increment() 78 | print(n) 79 | n.value += 'x' # will fail 80 | print(n) 81 | except: 82 | t.Rollback() 83 | print('-- rolled back') 84 | print(n) 85 | print('-- now doing stuff ...') 86 | try: 87 | n.DoStuff() 88 | except: 89 | print('-> doing stuff failed!') 90 | import traceback 91 | traceback.print_exc(0) 92 | pass 93 | print(n) 94 | -------------------------------------------------------------------------------- /Mediator.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | #coding:utf8 3 | ''' 4 | Mediator 5 | ''' 6 | 7 | import time 8 | 9 | class TC: 10 | def __init__(self): 11 | self._tm = tm 12 | self._bProblem = 0 13 | 14 | def setup(self): 15 | print("Setting up the Test") 16 | time.sleep(1) 17 | self._tm.prepareReporting() 18 | 19 | def execute(self): 20 | if not self._bProblem: 21 | print("Executing the test") 22 | time.sleep(1) 23 | else: 24 | print("Problem in setup. Test not executed.") 25 | 26 | def tearDown(self): 27 | if not self._bProblem: 28 | print("Tearing down") 29 | time.sleep(1) 30 | self._tm.publishReport() 31 | else: 32 | print("Test not executed. No tear down required.") 33 | 34 | def setTM(self, TM): 35 | self._tm = tm 36 | 37 | def setProblem(self, value): 38 | self._bProblem = value 39 | 40 | class Reporter: 41 | def __init__(self): 42 | self._tm = None 43 | 44 | def prepare(self): 45 | print("Reporter Class is preparing to report the results") 46 | time.sleep(1) 47 | 48 | def report(self): 49 | print("Reporting the results of Test") 50 | time.sleep(1) 51 | 52 | def setTM(self, TM): 53 | self._tm = tm 54 | 55 | class DB: 56 | def __init__(self): 57 | self._tm = None 58 | 59 | def insert(self): 60 | print("Inserting the execution begin status in the Database") 61 | time.sleep(1) 62 | #Following code is to simulate a communication from DB to TC 63 | import random 64 | if random.randrange(1, 4) == 3: 65 | return -1 66 | 67 | def update(self): 68 | print("Updating the test results in Database") 69 | time.sleep(1) 70 | 71 | def setTM(self, TM): 72 | self._tm = tm 73 | 74 | class TestManager: 75 | def __init__(self): 76 | self._reporter = None 77 | self._db = None 78 | self._tc = None 79 | 80 | def prepareReporting(self): 81 | rvalue = self._db.insert() 82 | if rvalue == -1: 83 | self._tc.setProblem(1) 84 | self._reporter.prepare() 85 | 86 | def setReporter(self, reporter): 87 | self._reporter = reporter 88 | 89 | def setDB(self, db): 90 | self._db = db 91 | 92 | def publishReport(self): 93 | self._db.update() 94 | rvalue = self._reporter.report() 95 | 96 | def setTC(self, tc): 97 | self._tc = tc 98 | 99 | 100 | if __name__ == '__main__': 101 | reporter = Reporter() 102 | db = DB() 103 | tm = TestManager() 104 | tm.setReporter(reporter) 105 | tm.setDB(db) 106 | reporter.setTM(tm) 107 | db.setTM(tm) 108 | # For simplification we are looping on the same test. 109 | # Practically, it could be about various unique test classes and their 110 | # objects 111 | while (True): 112 | tc = TC() 113 | tc.setTM(tm) 114 | tm.setTC(tc) 115 | tc.setup() 116 | tc.execute() 117 | tc.tearDown() 118 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | --------------------------------------------------------------------------------