Wednesday 31 August 2016

Design Pattern Haikus

Singletons

a singleton is
a global variable
sounds a bit better 

A singleton is just a fancy name for a global variable. I like to think of a singleton as a way of warping to another point in space/time, changing the space time continuum and then heading back. You've seen the sci-fi films where this happens, right? It has similar effects on your code, making it difficult to understand what the hell is happening.

Interpreter

interpreter is
domain specific language
that is all it is

Well, there's not much more to say is there? You want your code to be readable in the language of your domain. One way to do this is to make the code look more like the language of your domain. A domain-specific language is one way to accomplish this.

Visitor

multiple dispatch
that is what you really wanted
visitor will do

You've got a function that wants to do different things depending on the types of the arguments. You've got a language that only allows you to do one different thing via polymorphism. You don't want type-switching cos someone told you that was bad.

Assuming you've got those prerequisites then go for the visitor pattern. Alternatively, look at multiple dispatch and see there's no problem there at all really.

Strategy 

functions compose well
classes do not compose at all
love strategy pattern

You want to break apart a set of work into small discrete components (let's call them "objects"). The strategy pattern allows you to plug these together to solve a problem.

Or... You want to break apart an algorithm into discrete functions (let's call them functions). Functions glue together.