After a short digression into the prospect of an asteroid ending human civilisation and so making my Object Orientated Design and Programming exam on Tuesday something of a waste of effort, I am back to using the blog as a notepad and revision resource.
From the Gang of Four’s Design Patterns , I want to look at some of the structural software patterns: these are the patterns that cover issues such as composition.
The Adapter or Wrapper pattern allows classes that could not otherwise work together, work together, by converting the interface of one class into that which is expected.
The GoF use the example of integrating an “off the shelf” text editing component into a graphics package. The text editor may not have the interface that matches the graphics package, but an adapter can allow the two to work together.
Hopefully the bit of UML above makes it clearer – the client class calls the adapter in its
doWork() method, and it in turn calls the correct method in the adaptee. This is the “object adapter” pattern, but there also exists a “class adapter” pattern where the adapter inherits the interfaces of both the “expected” interface and the adaptee.
Composite – this pattern allows us to build structures of objects in the form of trees that contain both the objects and compositions of objects. We can apply the same operations over both the composites and the individual objects – the example given in Head First Design Patterns is of a
print() operation – we can apply this to any node in the tree to print it in whole or in part.
Decorator – this pattern allows new responsibilities to be added to an object dynamically – it is “decorated” with the additional responsibility. Decorator class methods must have the same signature of the decorated component but may have different behaviour.
Facade – this pattern provides a unified interface to a set of interfaces in a subsystem. The Gang of Four give the example of a compiler – which may have a simple
compile() interface method as opposed to exposing the complex series of commands needed to compile some code.
Proxy – this pattern provides an object as a surrogate for another object to allow control over access to the proxied object. The example the gang of four use is for a graphical object in a document, but these days a webpage may be a better example – for instance I have set the browser on one of my machines not to automatically load Flash. Instead I get a component I can click on to load the Flash if I wish (this means I am not flooded with the advertisers’ web bloat) – sound pretty much like a proxy pattern to me!
Bridge - this pattern places the implementation and the abstraction in two separate hierarchies and allows the two to vary independently.