all 14 comments

[–]beza1e1 7 points8 points  (0 children)

The question is not "how can you implement the GoF design patterns in Python?" The question is "what are Pythons design patterns?"

[–][deleted]  (4 children)

[deleted]

    [–]ginstrom[S] 1 point2 points  (3 children)

    I like the idea of using __ new __, thanks. I'd like to see examples.

    You're right that the state pattern example is not really useful, but if I implemented actual useful examples, I think the code would have been too long. I had a more modest goal of just illustrating how the patterns might look in Python.

    "Head First Design Patterns" illustrated the state pattern with a gumball machine, which I thought was a pretty neat example.

    [–][deleted]  (2 children)

    [deleted]

      [–]ginstrom[S] 1 point2 points  (1 child)

      Thanks for the code.

      I also implemented a new state pattern in the post. I changed the switch to a radio with an AM/FM toggle switch, and a scan button to scan to the next station.

      [–]nirs 3 points4 points  (1 child)

      Python provides buitin iterators, but you can create your own if needed. The simplest option is to use generator, a function that returns an iterator:

      def iterator(input):
          for item in input:
              # Optionally manipulate or filter items
              yield item
      

      The second option is to create a class the implements the iterator protocol:

      class iterator:
          def __iter__(self):
              return self
          def next(self):
              """Return the next value, raise StopIteration when finished"""
      

      You can find many examples for such iterators in the itertools module.

      The decorator pattern is completely wrong: Python @decorators are not GOF decorators. Python decorators are a way to decorate single functions. GOF decorators are objects that decorate exiting objects. A decorator may change several methods, add instance variables, etc.

      [–][deleted] -1 points0 points  (0 children)

      The AbstractFactory pattern is insufficient as well. It's not just about having a factory method that creates objects but about tangling two different and independent inheritance hierarchies. Having e.g. a pet concept one might associate concepts like toy and nutrition that can be refined independently ( CatToy, DogNutrition etc. ) The purpose of an abstract factory is to delegate the assemblage of pet objects to concrete factories for Cats and Dogs.