Head first design patterns - a1k89/Blog GitHub Wiki

helpers

Chapter 8. Encapsulating Algorithms: The Template Method Pattern

Steps:

  • Define abstract class
  • Define method inside it. For example, def cook(): pass
  • Define steps inside class
  • Write this steps inside cook
  • Also, you may to create hook - to coordinate with subclasses
from abc import ABC, abstractmethod

class Cooking(ABC):
    def cook():
        self.boil_water()
        self.add_ingredients()
        self.to_table()
     
    def boil_water():
        print("boil water")
    
    @abstractmethod
    def add_ingredients():
        pass

    def to_table():
        print("pass foods to table")


class CookOne(Cooking):
    def add_ingredients():
        print("add potato")

class CookTwo(Cooking):
    def add_ingredients():
        print("add banana")



cook1 = CookOne()
cook2 = CookTwo()

cook1.cook()
cook2.cook()

Chapter 9. Well-Managed Collections: The Iterator and Composite Patterns

With Iterator we incapsulate all mechanic of accessing to item in items

  • We must to create Iterator (has_next, next)
  • We must to pass this iterator to object
elements = ['Car', 'Cat', 'Dog', 'People']


class ElementsIterator:
    _position = 0

    def __init__(self, elements):
        self.elements = elements
        self.position = 0

    def __next__(self):
        try:
            element = self.elements[self.position + 1]
            self.position += 1

        except IndexError:
            raise StopIteration()

        return element


class MyAwesomeObjects:
    def __iter__(self):
        return ElementsIterator(elements=elements)


if __name__ == '__main__':
    awesome = iter(MyAwesomeObjects())
    while True:
        try:
            print(next(awesome))
        except StopIteration:
            break

    """ or """
    for el in MyAwesomeObjects():
        print(el)

Chapter 10. The State of Things: The State Pattern

  • Content

Chapter 11. Controlling Object Access: The Proxy Pattern

  • Content

Chapter 12. Patterns of Patterns: Compound Patterns

  • Content

Chapter 13. Patterns in the Real World: Better Living with Patterns

  • Content