Agile Zone is brought to you in partnership with:

I am a programmer and architect (the kind that writes code) with a focus on testing and open source; I maintain the PHPUnit_Selenium project. I believe programming is one of the hardest and most beautiful jobs in the world. Giorgio is a DZone MVB and is not an employee of DZone and has posted 637 posts at DZone. You can read more from them at their website. View Full User Profile

The Gang of Four patterns as everyday objects

04.27.2011
| 16960 views |
  • submit to reddit

A System Metaphor is what eXtreme Programming use to describe an architecture: for example you can think of particular application as production lines, or flying planes, or other kinds of machines. A metaphor has its limits in describing a concept, but it's really fast in being understood by programmers who are naive to the concept.

The original Gang of Four design patterns can be explained as real, everyday (and sometimes science-fictional) objects and actions. In this list, sometimes I use other software as the metaphor, as you will be already familiar with it if you are reading here. But I try to stick to physical objects and systems when possible.

Creation patterns

An Abstract Factory is a factory conforming to some specification, like a phone factory. The concrete phones you can buy are returned by this Factory. However, the standardization is not only in the interaction with the phones (each has 0-9 keys and a call button) but also in the interaction with the Factory (for example suppliers for large companies should follow standard supplier agreements).

A Builder is a very patient architect (the one that builds houses, not software): you tell him that you want the kitchen on this floor, and two bathroom and so on, but he cares about making it work and draw a complete design which accounts for electric wiring, pipes, structural integrity and so on.

A Factory Method is a cake mix; most of the work is already done and the recipe is written, but you may (or must) provide the missing ingredients when required by the recipe. The missing ingredient may also not be edible: the mold where you put the dough can be considered an abstract Factory Method.

A Prototype is a gremlin. Once you have it, you put it in the water and you can instantly create another one (beware not to feed your Prototype pattern after midnight.) Other metaphors are cell division, or any cloned animal like the sheep Dolly (actually only if you intervene on the genes it's a Prototype pattern: if you only create exact copies it's not very useful.)

A Singleton has no correspondence in real life, because it is in fact a bad idea. It will be like a sheet of paper that when written manages files in your pc, or a credit card that charges itself without a PoS. Some says titles such as the US president can only be held by one person, so they are Singleton. Yet there are many presidents (Clinton, Bush, Obama...) and if you ship products in Europe they don't really need a reference to the US president.

Structural patterns

An Adapter can be simply an AC adapter for laptops, but also any kind of electrical adapter between different outlet types. Every geek has lots of adapters in his house so this is the easiest pattern to explain.

A Bridge is an operating system which uses drivers (thus, every OS). The interface for the client (fopen() and similar functions) are evolved separately from drivers for hard-disks, optical devices, and Flash memories.

Continuing with the electrical metaphors, a Composite is a power strip, where you can plug in many devices with a single outlet. In mathematics instead, every arithmetic expressions is a Composite which can be combined with other ones to build a longer, more complex expression.

A Decorator is a layer of colored glass: in particular sunglasses and augmented reality (or 3D) glasses fit the pattern. They do not change your interface with the world (pair of eyes), but they are interchangeable, add some kind of behavior or filtering and can be overlapped in any order.

A Facade is a customer support desk, or even a wedding planner: he hides from you the complexity of a large subsystem. The wedding planner orders flowers, makes reservations, organizes everything for you.

A Flyweight: preforked processed on the web server, although that says nothing about the idiomatical implementation of flyweight we use in oo languages

A Proxy is each SSH client you run to access a shell on another machine. Also VNC and other graphical proxies are equivalent.

Behavioral patterns

A Chain of Responsibility can be thought of as a military chain of command, where each request may be escalated to the superior officer. Also some business are an example, at least the ones that let you say "Can I talk to your boss?"

An example of custom-made Command can be a restaurant order. The operation, comprehending many different dishes and beverages, is packaged up in a single object which is passed around. The order arrives in the kitchen and is executed without direct interaction with the customers.

An Interpreter is really hard to find in the real world. The software version is really complex to apply and if you can find a metaphor, I will be glad to add it to this article.

An Iterator is difficult to discover as a physical object. An example I found on the web is that of a TV remote: it represents channels in a linear model for you, even skipping the empty ones. However, channels are actually segregated in many bands and frequencies, but this complexity is hidden.

The Mediator: in many democracies, the members of Parliament and other assemblies may not address each other directly, but only talk to the head speaker of the house (to avoid confusion). The same happens in airports, where an Air Traffic Control tower redirects planes around without them having to communicate with all the others.

A Memento is implemented by saving button of applications. File formats are a Memento of the in-memory data structures used in word processors, spreadsheet and similar: when you save, you translate a bunch of objects into a serialized version, or more likely a completely new representation. These days, the target representation is standardized: .doc, .odt and so on.

Observers are very diffused both in software and in the real world. For example, at the library you add a listener for books which are out but will return soon: you will be notified when the status of the book changes (usually because a copy is available). If N users are observing M books, there is no added complexity to their interaction with the library.

For a technological example, consider RSS and PubSubHubbub: with this extension, your reader subscribe to an hub which stays in the middle between him and your feeds. The reader is instantly notified by the hub when the latter detects updates.

State: the behavior of many electromechanical machines can be modelled as a set of states and transitions.

As an example, a microwave oven has at least two states: door open and ready for heating. You can jump from one state to another due to an external input; in each state, the behavior is different and the State pattern is about keeping these difference in different objects, so that adding new states does not touch a large part of existing code.

A Strategy is any company policy or document procedure: a document injected in the system to regulate some behavior. You can easily change this document when the time comes, without impacting the system around it, which is really working well.

Template Method: if you want to be a confectioner as a side job, you can easily buy a pastry bag. This object specifies a Template Method for decorating cakes with creams or meringues. You can change the tips to put on its lower end (by subclassing this hook method), to specify the output yourself. If you don't specify an output form, the bag won't work correctly.

Visitor: a supermarket's cashier is a Visitor of your basket of goods. With Double Dispatch, you hide the structure of the container, which can be a real basket, a trolley or just your hands. When you arrive at the cashier's, in fact you hand out the products over the counter.

Other sources

http://wwwswt.informatik.uni-rostock.de/deutsch/Lehre/Uebung/Beispiele/PatternExamples/patexamples.htm

http://www.programmersheaven.com/2/Tutorial-Design-Patterns-Structural-Decorator

http://java.dzone.com/articles/design-patterns-visitor

Published at DZone with permission of Giorgio Sironi, author and DZone MVB.

(Note: Opinions expressed in this article and its replies are the opinions of their respective authors and not those of DZone, Inc.)

Comments

Bruce Baron replied on Wed, 2011/04/27 - 3:54pm

A power strip isn't a good metaphor for the Composite pattern. It doesn't represent a whole-part hierarchy

Nicolas Lochet replied on Thu, 2011/04/28 - 7:10am

Interpreter is not to hard to find in reality, it's even a job name. The interpreter help you communicate with someone you don't know the language because he can translate on the fly.  ^_^

As a pattern it define a class knowing your language (ie your datamodel) and another external language. An ORM layer is a very good exemple of two way interpreter (OO <=> RDBMS) everbody can use without knowing it is an interpreter pattern instance.

(I also add that the job known as translater is equivalent to a compiler in a computer sense, doing the job in his own office and providing you the result in a file in the end).

Javin Paul replied on Thu, 2011/04/28 - 9:40am

Excellent stuff man , you indeed covered the topic in details with some really good example. design pattern is little complex topic until you understand where to use and where not use and how to use it. I would prefer to give some don't also i.e. where not to use this pattern and also what is benefit of using it how it helps in maintenance etc. e.g Factory pattern helps a lot if you want to create new object because you only need to make change on Factory class ,why because Factory encapsulates logic of creating object , so it require to change in one class which means less testing, less chance of error and quick delivery. Anyway great stuff and keep it up.

Javin
Why String is immutable in Java

 

Giorgio Sironi replied on Thu, 2011/04/28 - 4:35pm in response to: Bruce Baron

@Bruce: My reasoning was you can swap a powerstrip (N attached devices) with a single device, because they have a common interface. A power strip is only a piece of the pattern.

Giorgio Sironi replied on Thu, 2011/04/28 - 4:36pm in response to: Nicolas Lochet

@Nicolas: The GoF Interpreter defines a hierarchy of classes for doing the job, which is far more restrictive for finding an example than a layer of translation. :)

Giorgio Sironi replied on Thu, 2011/04/28 - 4:37pm in response to: Javin Paul

@Javin: as you see, the article is already long, so I stuck to giving a metaphor for each pattern.

Andrey Kanash replied on Fri, 2011/05/06 - 9:35am

Interpreter: Any kind of emloyee. Receives information or materials and creates an output.

Comment viewing options

Select your preferred way to display the comments and click "Save settings" to activate your changes.