Over a million developers have joined DZone.

The Gang of Four patterns as everyday objects

DZone's Guide to

The Gang of Four patterns as everyday objects

· Agile Zone
Free Resource

See how three solutions work together to help your teams have the tools they need to deliver quality software quickly. Brought to you in partnership with CA Technologies

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




Discover how TDM Is Essential To Achieving Quality At Speed For Agile, DevOps, And Continuous Delivery. Brought to you in partnership with CA Technologies


Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}