Tuesday, 17 June 2014

Learn A Pattern A Week With Pie - Singleton

Our focus this week shall be on a very simple yet useful design pattern, the Singleton Design Pattern.

So What's The Singleton Design Pattern?

Like a lonely guy, a singleton class has one and only one object instantiated application-wide. The Singleton pattern is categorised as a creational pattern because it provides a very good way of instantiating objects.

This pattern usually involves a single class which takes absolute responsibility of creating it's own object while ensuring no one else does and also ensuring that only one object gets created. A singleton class also provides access to it's only object directly without the need to instantiate an object of the class.

Classes whose purpose is to provide application-wide services are good candidates of the singleton design pattern. To this effect, the singleton pattern is used for components like Loggers, Drivers, Thread Pools, Caches etc.

What Does It Take For A Class To Be A Singleton?

Note that, the whole essence of the singleton design pattern is to ensure that only a single instance of a class exists application-wide and this single object should only be created by the class itself. This means the following conditions should be met:

1. A Private Constructor : The singleton class should have a private constructor to ensure that no object of the class can be created outside of the class itself. Without a public constructor no other code can create an instance of a class. Making the class' constructor private prevents other classes from creating objects of this class. In this case, only the class under discussion can create an object of it's own self.

2. A Private Static Instance : There also need to be a private static instance of the same class that is the only instance of the class. Since an object of the class can never be created outside of the class, we'll need to explicitly instantiate an object of the class under discussion. This single instance should be made static and preferably final as well just so we wouldn't have to instantiate an object of the class (which can't be done anyways) before accessing it.

3. A Public Static Method : This static public method (usually named 'getInstance()') is the global access point for the outer world to get a reference to the single instance of the class under discussion.

I think we've had enough theory to get you confused now! Let's do a hands-on exercise to clear the confusion.

In our hands-on exercise, we'll create a hypothetical database connector class which should help us to execute queries any where within our application. NOTE : We won't actually do any database programming here, we'll only simulate the operations.

In this exercise, we've created a pseudo database connection manager with a public API which is supposed to return a list of all the employees in our database. Assuming this data is so central to our application that we'll want to be able to access it anywhere in our codebase without having to explicitly instantiate objects of our DatabaseManager class, we've made our DatabaseManager class a singleton class.

This means anytime we want to access the list of employees in our database, all we've to do is to call DatabaseManager.getInstance().getAllEmployees();

DatabaseManager.getInstance() will return the only instance of our DatabaseManager class which we'll want to exist application-wide. We then invoke .getAllEmployees() on the instance returned.

Traditionally, we would have written the following lines of codes anytime we wanted to access our employees records.

DatabaseManager dbManager = new DatabaseManager();

The above code does not only demand that we type too much characters, it also wastes system resources because anytime a new DatabaseManager object is created, the database connection driver will have to establish a connection to the underlying DBMS and also perform some house-keeping chores.

Implementing this class as a singleton will ensure that our database connection driver performs it's bootstrapping chores only once. It also ensures that only a single instance of this class exist which helps us to keep a global representation of our class.

Note that we've used a database manager in this example but you can always use the singleton design pattern whenever you want to create a class to provide application wide services.

This is the simplest way to implement a singleton class. We'll take a look at other variants later.

Meanwhile, leave your questions and suggestions using the comments box below and let's learn together.

Let's write clean codes one character at a time!!!

Monday, 16 June 2014

Learn A Pattern A Week With Pie - Overview

As promised, we're gonna learn a new design pattern each week to make us better programmers, programmers who write clean and maintainable code. If any code was ever written by a good programmer, that code would probably not need to be commented.

To make the learning easier and full of fun, am gonna make my post very simple, byte-sized chunks which can easily be learnt, understood and memorised in the shortest possible time.

Today, I'll give you an overview of the various groups of design patterns out there and also learn about the GOF.

So What Is The GOF Thingy?

GOF (Gang Of Four) refers to a group of 4 authors Erich Gamma, Richard Helm, Ralph Johnson and John Vlissides who in 1994 published a book titled "Design Patterns - Elements Of Reusable Software" which initiated the concept of design patterns in Software Development.

I just felt I should make mention of these reverend authors and pioneers of such an important subject in Software Development since no self-respecting book or text on this subject matter would be complete without making reference to the Gang Of Four.

Types Of Design Patterns

Per the book Design Patterns - Elements Of Reusable Software written by the GOF, there are 23 design patterns classified into 3 major categories: Creational, Behavioural & Structural Design Patterns.

In my subsequent posts we'll study each of these 23 design patterns identified and outlined by the GOF in their book.

Meanwhile, let's take a look at the criteria for grouping these 23 design patterns into any of the 3 categories.

NOTE : Java will be used for the code samples in all my post. It shouldn't be difficult converting those sample codes into other OOP languages!


Instead of using the "new" keyword in Java to instantiate new objects of classes, the creational design patterns provides ways of creating objects whiles hiding the logic for creating the objects. This gives more flexibility in deciding which object needs to be created for a given use case unlike using the "new" keyword.


These patterns are concerned with how objects within our programs communicate across their interfaces.


These patterns concern classes and objects compositions. In these patterns, inheritance is used to compose interfaces and define ways to compose objects  to obtain new functionalities.

Don't worry if all these seem too abstract and incomprehensible. Just hold on for a ride and things will be better once we start studying all the 23 patterns one-after-the-other.

May today kick yesterday's ass!

Friday, 13 June 2014

Learn A Pattern A Week With Pie - Introduction

What Are Design Patterns?

Design patterns are a documented set of best practices used by experienced object oriented programmers. These are solutions to general problems that these experienced programmers once faced during software development. Through numerous trials and errors, these solutions were finally obtained, standardised and documented over quite a substantial period of time.

Why Should I Care About Design Patterns?

Design patterns have evolved over a period of time and they provide splendid solutions to certain problems faced during software development.

The un-experienced or green-horn programmer will learn software design in an easy and faster way. Learning design patterns will help you avoid common mistakes which experienced programmers made in the past. This way, you'll be saved an invaluable quantity of time which you can use to do something else.

Design patterns also set a common platform for programmers. It provides a standard set of terminologies which are specific to particular scenarios. For example, a singleton design pattern signifies use of a single object application-wide so all programmers familiar with this terminology will make use of a single object and can tell each other that program is following the singleton pattern.

Design patterns also set a yard stick with which we measure clean codes. Learning design patterns will help any programmer to avoid writing hard-to-maintain-code. Design patterns will help you develop software packages which are closed to modification but open for extensibility.

In my own opinion, one good way of becoming a good programmer is to follow the following route:
1.    Choose one main-stream and one non-main-stream language. Eg Java or C#.Net & Python or Go
2.    Master the Syntax & Semantic of the languages you've chosen
3.    Master the Object Oriented Concepts & Constructs. Eg Polymorphism, Encapsulation etc
4.    Master Design Patterns and know how to apply them in your languages of choice.
5.    Write & Read a lot of code
6.    Never enter tomorrow being the same person you are today. Learning is a life-long process.

If you enjoyed this post, join me as we learn a new design pattern every week.

Enjoy your weekend!