Basic design patterns and a book recommendation
February 23rd, 2008
About a year ago I got interested in the complexety of design patterns for better solving problems in software development you are circularly confronted with. When reading “Head First Design Pattern” by Eric Freeman, Elisabeth Freeman and Kathy Sierra I soon mentioned that I use the common ones of them without having recognized it before.
I’m not as surprised about that as you might think ’cause there a several problems in software development you can just solve that way or you chose kinda “dirty” way. Even thougth the book is exhausting to read ’cause it’s not written the way most book for programmers are - it’s really abstract which means they’re almost never writing about problems that occur the development of a software product but all-time about compareable situations in real life. None the less I can without any doubt recommend it to you as a book every programmer should have read once or maybe twice.
To give you a short preview I’d like to tell you about real basic patterns you might already know very-well.
All code examples are written in Java, not because I do like Java that much, rather ’cause Java is qualified to be readed easily particularly concerning object orientated programming techniques. It doesn’t have much overhead in syntax that would distract you from the things I really want to you see. Of course patterns are used in every object orientated language they just differ form each other by the way there’re syntactical written and some programming languages have features that help to implement them easier.
- The Factory Method
- The Abstract Factory Method
- The Builder Pattern
- The Prototype Pattern
- The Singleton Pattern
It’s its intention to separatly construct a complex object so that the same construction process can create different representations.
It provides a simple decision making class which returns one of several possible subclasses of an abstract base class depending on data it is provided.
If there’s more than one way to created an object factory methods are right choice. Especially when the class that calls a factory method delivers the required information for creating an instance.
The factory method pattern should be used in those cases:
* The class that calls the factory method doesn’t know exactly what instance has to be created.
* The calling class is not pretty sure howto created the needed instance.
* The calling class gives information to the factory method that helps/is required to created the needed instance of an object.
* The class that provides a factory method to gives permission of its creation to its subclasses.
Factory methods are common in toolkits and frameworks where library code needs to create objects of types which may be subclassed by applications using the framework.
This example of a facotory method creates an instance of an ImageReader. Each time the program reads an image it needs to create a reader of the appropriate type based on some information in the file.
public class ImageReaderFactory { public static ImageReader getImageReader( InputStream is ) { int imageType = figureOutImageType( is ); switch( imageType ) { case ImageReaderFactory.GIF: return new GifReader( is ); case ImageReaderFactory.JPEG: return new JpegReader( is ); // etc. } } }
It provides an interface to create and return one of several families of related objects. It encapsulated a group of individual factories that have a common theme.
Abstract factory methods work like classic factory methods but they’re a bit enhanced. Using them is recommented when:
* A class should work totally independent from the creation of the instances of objects it works with.
* A group of objects shall be created ’cause they’d be used together
* A class library should offer a whole bunch of implementations.
Typically you find it in GUI libraries that offer different themes for their controls.
At first we design a abstract factory that looks very clear:
public abstract class AbstractGUI { public Button CreateButton() { return new Button(); } }
Afterwards two concret class get designed that extends the abstract class and its methods override the deliverd ones.
public class XPStyle extends AbstractGUI { @Override public Button CreateButton() { return new XP_Button(); } } public class GnomeStyle extends AbstractGUI { @Override public Button CreateButton() { return new Gnome_Button(); } }
The GUI class has a method for the name of a control:
public class AbstractGUI { private String name; public String getName() { return this.name; } public void setName(String name) { this.name = name; } }
This is the most important part, that is used when a particular button is created:
public class XP_Button extends Button { public XP_Button() { super(); setName(âXP Buttonâ); } }
Eventually the great advantage of this is that you don’t have to worry about what kind of objects you’re building the factory does ease your workload.
It can be used to clearify a complex building progress of an big object.
This should explain how a abstract builder works:
abstract class ButtonBuilder { protected Button button; public Button getButton() { return button; } public void BuildNewButton() { button = new Button(); } public abstract void buildStyle(); }
In this class the concret building is done:
class MySuperButtonBuilder extends ButtonBuilder { public void buildStyle() { button.RoundBorders(1); button.FancyLook(1); } }
It separates the construction of a complex object from its representation, so that several different representations can be created depending on the needs of the program.
The prototype means making a clone. This implies cloning of an object to avoid creation. If the cost of creating a new object is large and creation is resource intensive, we clone the object. We use the interface Cloneable and call its method clone() to clone the object.
public class Data implements Cloneable { public Object clone() { try{ return this.getClass().newInstance(); } catch(InstantiationException e) { e.printStackTrace(); return null; } } } public class DataCreator { private Data d; public DataCreator(Data d) { this.d = d; } public Data GetData() { return (Data)data.clone(); } public Object clone() { } } public class SecretData extends Data { //concrete prototypes to clone }
Working with that can be done in that way:
Data dataprotoype = new SecretData(); Data mydata = new SecretData(dataprotoype); for(int i=0; i<100; i++) tmpData = mydata.GetData();
It starts with an initialized and instantiated class and copies or clones it to make new instances rather than creating new instances.
Is the one that provides a class of which there can be no more than instance, and provides a single global point of access to that instance.
Sometimes it’s appropriate to have exactly one instance of a class: e.g. for window managers, print spoolers etc.
The most common usage is a logging class that does something with alle logs and exceptions that are thrown.
If an object is needed in the whole application a singleton is better than a real global object. But you’d also be careful when implementing lots of singletons ’cause you surly don’t want
give up object orientation and have everything globally just for easier usage.
A singleton should give you those possibilies:
* Create the only existing object of a class
* Provide a global point of access to the object (getInstance(); ).
The first thing you’ve to do when avoiding the creation of multible objects from one class is to set the constructor to private access.
Then you’ve provide your own method for creation of an object that checks if another object exists before creating. Easy but effective!
private static Logger log; private Logger() { //private constructor } public static Logger getInstance() { if (Logger.log == null) { Logger.log = new Logger(); } return Logger.log; }
To improve this solution we’d make it thread-save. Java provides a synchronized keyword that ensures the synchronized access. Java makes it really simple, C# needs a variable that is volatile (indicates that a field can be modified in the program by something such as the operating system, the hardware, or a concurrently executing thread.) which is check before creating a new object.
public static synchronized Logger getInstance () { if (Logger.log == null) { Logger.log = new Singleton (); } return Logger.log; }
Design patterns are an extensive topic you could write about for hours. My aim was just the give you a thorough insight into that issue without going to deep and making it more complex than necessary.
To have basic ability in using those patterns is also important ’cause when discussing with other programmers you don’t want to discuss the whole logic you’ll write you just want to discuss about a certail technical term and if it matches to solve the given problem.
Here you can buy Head First Design Patterns published by O’Reilly on Amazon.com






