Quick overview of really useful Design Patterns

Design Patterns capture a common combination of computer code; code that creates things, code that’s in a certain structure or code that behaves in a certain way. These Design Patterns help to solve common problems in similar structured ways, enabling programmers to get to a solution faster, communicate their ideas with other programmers quicker and write code that is more easily recognised and understand by others. So here are a few of the well known design patterns that we commonly use.

Observer / Observable (structural pattern)

The best example is the spreadsheet. Think of all the cells and calculations as business logic and data (the model) – this is the observable bit. A line graph, a pie chart or a pivot table all subscribe to the Observable model as Observers. When the model changes, it goes through it’s list of Observers and tells them it’s been updated.

Observable { addObserver(), notifyObservers() },

Observer { notify() }

To extend this to Model View Controller (MVC), think of a GUI interface. Windows, OSX etc. have, as part of their operating system, a windows and pointer interface. The OS acts as a controller, intercepting any mouse clicks or other mouse events (over, move etc.) and then deciding which part of the model is to be given the mouse event, e.g. which application is in the foreground. The application (model) updates itself and then notifies when it’s complete and it’s windowed display updates.

Struts and Spring MVC are also implementations of Observer / Observable, with the extra controller bit. The web request comes in and (in Spring’s and Struts’ cases) a servlet is used to dispatch the requested to a delegated controller (spring) or action (struts). The controller should do very little except marshall any data from the request and then call the appropriate model method. Upon the model’s return, a view can be rendered, usually only one. In this respect, MVC breaks the Observable idea because the controller is responsible for deciding which view to return, rather than ALL views being updated because the model has changed. This is mainly due to the single thread of I/O between a web client and web server. However, the view type is decided during the request and a html, PDF, excel, video etc. view can be returned.

Singleton (creational pattern)

It has a private constructor, so it can’t be instantiated directly. Instead, a static method creates the object. This static method first checks to see if a static variable already has an instance of the object, if so it returns it, if not, it creates the object, sets it in the static, then returns it. Ensuring only one object of that class can ever be created in the application.

Factory (creational)

The factory pattern normally consists of a Creator interface and a concreteCreator implementation. It’s often used if you want to create the same sort of things but in different ways. The Creator interface will have one or more methods that create objects, E.g. CreditProcessorCreator has methods createLoanProcessor() (returns a LoanProcessor object), createOverdraftProcessor() (returns an OverdraftProcessor object) – A concrete instance of Creator can then be used to produce these objects but they might be configured in different ways or the actual objects might be subclasses. E.g. WebRequestCreditProcessorCreator produces objects that are created and listen to incoming web requests for their data. MessagingCreditProcessorCreator produces objects that are configured instead to listen to data from a messaging queue.

Builder (creational)

Another creational pattern that’s used to construct complex objects. In a reporting application that generates overnight survey result summaries, a Builder is used to create the different bits of a PDF document. For example, a PageBuilder, with methods: buildTitle(), buildChart(), buildSummary(), buildKeyResults(). This means that a PDFPageBuilder creates and builds a PDF document. There could also be a HTMLPageBuilder that does the same but creates HTML output instead of PDF. There’s a ReportDirector that doesn’t care about HTML or PDF, it just needs the appropriate builder to be passed in and the report data needed by the builder methods.

Composite (structural)

Very important one this. It’s a pattern for “belongs to” relationships. For example, an employee has a manager, who in turn has a manager etc. This can be put into a single table in a database, with an employe table having a foreign key to another employee row (the manager). However, Hibernate (an Object to Relational Database Mapping System) doesn’t allow for any mappings that refer to itself. It can’t be done. The composite pattern provides a neat way of getting around this.

Using a shop as an example, there are categories, sub-categories, sub-sub-categories etc. and products that belong to a category. Categories are the Composite and products are the Leaves.

Both the product (leaf) and the category (composite) has a shared super class, Component. In our shop, we call this an Item. So the product is a type of item and the category is also a type of item. Our category (composite) maintains a set of Items (components). This makes our outputting our shop contents very easy because every item has a title, description and an image. So for any given category (composite), we can get it’s set of Items and display them. It doesn’t matter whether it’s a product or a category.

In the database, we have an Item table and a product table, with a foreign key to item and a 0 or 1 relationship. In the category table, we have a foreign key to the item, with a 0 or 1 relationship AND another foreign key to Item with a 0 or many relationship. So the tables don’t refer to themselves and we don’t have the hibernate self-referncing problem. It’s a bit more complicated but we get to distinguish between Products and Categories very nicely too.

Strategy (behavioural pattern)

Using the same interface to process objects in a different ways, for example, in orderProcessing, you might wish to process pre-orders, orders-in-progress and completed orders in a different way, but they’re all orders.

We can setup an OrderProcessStrategy interface with it’s method, processOrder(), then create implementing classes of PreOrderProcessStrategy, InProgressOrderProcessStrategy etc.

The context that the strategy will be used in, therefore, is passed in at runtime. An OrderProcessor object may have a method: processOrders(OrderProcessStrategy) – this method will fetch all orders but use the strategy to process them. This makes it easy to report on orders in different ways and add new reports.

Decorator (structural)

A useful pattern for providing sub-classing without actually doing sub-classing. I use this all the time, very handy. The Eclipse development environment even has a menu option to create decorator methods. For example, if I want to create a specialised kind of collection. I might create an object called MyCollection implements List and set an instance variable in it: ArrayList list = null; I can then highlight my “list” variable in eclipse and from the refactor menu, choose Delegate. This will then (like getters and setters) create all the methods that arrayList has thus satisfying the implementation of the List interface. MyCollection now behaves just like an ArrayList would. However, I can now override each method with any special behaviour.

This is especially useful if you find you need to sub-class a class declared as Final. It’s also good if you find yourself breaking the Liskov substitution principal.

Facade (structural)

Kind of like decorator but pulls together many objects and puts most of their methods in one place. It means that someone programming to a complex API with hundreds of objects can just use a simple, single object interface to do all the work.