dedicated to write powerful yet elegant software by using minimum code and maximizing the benefits for all our clients.

Design Patterns - A deep dive 3 by Sunny 06/Jul/2008 23:14:00

Welcome to a series of articles on design patterns. 

In the previous articles, we have covered the following areas:

Part 1 - looks at design patterns at a high level to understand what they can/can't do.

Part 2 - looks at the basic categorization of the patterns & a one-line definition of each pattern under that category.

The previous two parts have been a very high level overview of design patterns. The articles henceforth will concentrate on a single pattern & hopes to provide an insight  regarding coding the pattern, uses of that pattern & some common gotcha's while using that pattern. 

This article (Part 3) looks at one of the simplest and most commonly used type of Creational Design Pattern called as the Singleton Design Pattern. 

What is a Singleton Pattern?

An instance of a class is considered Singleton if it meets the following criteria:

  1. There is only one instance of the class during the lifetime of that application
  2. Any attempt to instantiate another instance of this class would return the previously created instance
  3. The constructor of this class is either private or protected only.

Why is Singleton Pattern classified as a Creational Pattern?

Creation design patterns are a category of design patterns in which there is some special process in the "creation" of an instance of a class.

In case of Singleton pattern, the constructor of the class is not accessible & so an instance of that class cannot be created. The class will internally create an instance of itself & return a handle to this instance each time.

Due to this special behavior of the constructor, this pattern is classified as a Creational Pattern.

Lets talk code

Consider a simple class called Singleton which implements this pattern as shown:
public class Singleton{
 
    private static Singleton m_INSTANCE = null;
 
    private Singleton(){}
 
    public static Singleton GetInstance(){
 
        if(m_INSTANCE == null)
            m_INSTANCE = new Singleton();
 
        return m_INSTANCE;
    }
}

The interesting features of this class are: the constructor, the method GetInstance() and the private static Singleton type field m_INSTANCE, which we will get into more deeply in the following sections.

The constructor

The constructor of the Singleton class has been declared private. You could also declare it protected. Any other modifier like public or internal would allow a possibility to create an instance of this class & would defeat the purpose of a Singleton.

private Singleton(){}

The main concept to understand here is that we are restricting creating the instance of this class by setting the access modifier to the constructor. So, now no consumer of the class can create an instance of it. The only way we can get get an instance is to call the GetInstance() method & use that instance.

The field m_INSTANCE 

The field m_INSTANCE is a private static field which will hold the object of the Singleton class.

private static Singleton m_INSTANCE = null;

Since this field is lazy-initialized & the GetInstance() method always returns this object, we have been able to control the creation of instances for the Singleton class.

The GetInstance() method

The GetInstance() method is the only way we would be able to get an instance of the Singleton class.

public static Singleton GetInstance(){
 
    if(m_INSTANCE == null)
        m_INSTANCE = new Singleton();
 
    return m_INSTANCE;
}

In the class shown above, we note that we are lazy-initializing the private static Singleton type field m_INSTANCE. This code ensures that there would be only one instance of the type which will be created the first time GetInstance() method is called. For any other call after this, the object stored in m_INSTANCE will be returned without creating a new instance.

The point to note about the GetInstance() method is that it has been declared public static with a return type of Singleton. As mentioned previously, since the constructor is private/protected, we will not be able to create an instance of the class & so we will need this static method to get the instance.

Uses of Singleton Pattern

The Singleton pattern is extremely simple to implement & use. Typically, items which need to be initialized only once during the application life implement this pattern. Some of the common examples of such items can be: User Preferences & Settings, Thread/Connection pools, context objects, handle to Application Services (logging, data access, error handling etc.)

In short: "Singletons are most appropriate for services that donot change change their nature based on their invocation context" (c2.com, 2008)

The Bells & Whistles

In this section, we will look at some interesting items which need to be kept in mind while using the Singleton Pattern which might actually make it evil:

  1. Singleton's v/s Global Variables - IMHO while Singleton's are a classes where we are restricting creating mutiple instances, global variables are more like "declared instances". Given this mindset, I would expect a Global Variable to be changed during the lifetime of an application based on certain conditions in the application, while a Singleton would remain in the same state. One more difference I note is that Global Variables are truly global to the application, but a Singleton could be accessible to a part of the application/thread.
  2. Singleton's & performance - One of the most important decisions while using a Singleton is when do we actually instantiate the members of the class & how expensive is it to keep this instance in memory? In the code sample shown previously, we had lazy initialized the m_INSTANCE member which was sufficient for that case. But given a more complex or expensive resource to create, we need to re-look at our design & check if it makes sense in having a Singleton or use some other mechanism.
  3. Singleton's & state - One of the core concepts of Singleton is that it maintain its state as long as the application lasts. One of the drawbacks of this is that to load a different state (For example: running Unit Tests), we need to expose methods to set the new state, which quite defeats the idea that Singleton's retain their state. The other alternative is to reload the application with a different state for the Singleton instance, but then is this acceptable for a Unit Test?

Wrap up

In this article we have seen how a Singleton class can be created, what are its main elements. I would love to hear your thoughts, ideas & experiences using the Singleton Pattern.

In the next article, we will look at another Creational Design Pattern.

Currently rated 4.0 by 1 people

  • Currently 4/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Tags: , ,

Category: Design Patterns | Development

Design Patterns - A deep dive 2 by Sunny 30/Jun/2008 21:47:00

Hey there! Welcome to second part of a series of articles on design patterns.

In case you tuned in late, the previous article looked at what design patterns could/could not do & some reasons why we need to use them. In this article, we look at the evolution of design patterns, categorizing the design patterns & their definitions, and a list of all the different patterns out there.

Once upon a time...

Once upon a time in a land far away there lived an achitect (who designs & builds buildings for a living, duh!) by name Christopher Alexander who produced a pattern language as: an architectural concept to empower any human being to design & build at any scale

Kent Beck & Ward Cunningham began experimenting with these ideas to apply them to software. They presented using pattern languages for object-oriented programs at the OOPSLA & the rest was history.

Design patterns were here to stay with important contrbutions from THE Gang of Four & THE Martin Fowler to name a few experts in this area of work.

Moral of the story:
Its cool to be an "architect" in a software company, with having nothing to do designing & building buildings!

The Classic Categorization of design patterns

Creational These set of patterns deal with special mechanisms to handle the creation of objects
Abstract Factory used to create an instance of several families of classes
Factory used to create an instance of several derived classes
Builder
seperates object construction from its representation
Lazy initialization delays the creation of the object till the first time it is needed
Object Pool
maintains & releases a pool of resources by recycling objects
Prototype
used when the type of object to create is determined by the prototypical instance, which is cloned to produce new objects
Singleton
restricts to hanving only one instance of the class
Structural These set of patterns identify a simple way to realize the relationship between entities
Adapter provides a mechanism to match the interfaces of two classes
Bridge
seperates an abstraction (Interface) from its implementation (class) so that both can vary independantly
Composite
compose objects into tree structures to represent part-whole heirarchies
Decorator
used to add new/additional functionality to an existing class dynamically
Facade
used to provide a single interface to a larger set of interfaces by hiding that large set
Flyweight
is an object  that minimizes memory occupation by sharing as much data as possible with other similar objects
Proxy
is an object which represent another object that is expensive to duplicate
Behavioral These set of patterns identify common communication patterns between objects
Chain of responsibility a way of passing a request between a chain of objects
Command
encapsulate a command request as an object
Interpreter
a way to include language elements in a program
Iterator
sequentially access the elements of a collection
Mediator defines simplified communication between classes
Memento
capture and restore an object's internal state
Observer
a way of notifying change to a number of classes
State
alter an object's behavior when its state changes
Strategy
encapsulates an algorithm inside a class
Template defer the exact steps of an algorithm to a subclass
Visitor
defines a new operation to a class without change

Source: dofactory.com

Domain-specific patterns

Besides the classic categories of design patterns as shown above, there is a very huge list of patterns, some of which are domain-specific. Some examples of such patterns are UI design patterns, concurrency patterns, AJAX patterns, Web development pattern etc. which focus on solving software design issues for that domain.

Not a silver bullet

There have been numerous crticisms of design patterns here and here and an interesting defense too! As pointed out in the previous article, design pattern is no silver bullet. It is just a framework to get our mind around to understanding a problem. 

So, if this framework helps in solving a design problem, that is cool; if not, that is cool too - is my take on this subject. 

Lotsa text, wassup next?

We are done with understanding some history of design patterns, their categorization & some definitions of what each pattern means.  

The next article promises to be more fun as we will start looking at the actual implementation of the patterns in terms of code, identify a few real-life examples where we can use it & hopefully get to hear your experiences & gotcha's with the pattern.

So stay tuned, code coming up!

Currently rated 2.0 by 2 people

  • Currently 2/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Tags: , ,

Category: Design Patterns | Development

Design Patterns - a deep dive 1 by Sunny 28/Jun/2008 17:16:00

A colleague of mine asked me a question few days back: "If an application is created using the correct design patterns, does it ensure that the application would be bug/performance issues free?"

The answer to the question gave me an idea to put in a series of articles to look at what are design patterns, what design patterns can/can't do & hopefully get some interesting dialog started with you readers about your experiences & inputs.

Let us start this journey with a small step in understanding a few definitions regarding design patterns, and look at what design patterns are all about at a very high level. The subsequent articles will focus on details of each pattern & a few scenarios where we can use these patterns. 

What is a design pattern?

"In software engineering, a design pattern is a general reusable solution to a commonly occurring problem in software design" - (Wikipedia, 2008

IMHO, a design pattern is a probable way to solve a design problem in software. I use the term "probable" because even though a design pattern might "seem" to solve the issue you are facing, you still need to analyze the problem & ensure that the solution/pattern offered is valid in the context of your development effort.

This judgement is acquired only by experience in either using the pattern successfully or having burnt your fingers in the process. Experienced Architects, Designers & Developer will tell you that even if you have had used a pattern many times in your previous projects, you will still need to evaluate using the pattern in your current project simply because the requirements/project environment/time-of-the-day is different from the last time you used it.

"Patterns are about design and interaction of objects, as well as providing a communication platform concerning elegant, reusable solutions to commonly encountered programming challenges." - (Data & Object Factory, 2008)

The key word in the definition above is the idea of a "communication platform". A design pattern not only helps in communication between objects, but also provides a communication platform in discussing your ideas with your peers.

For example, it would be easier in telling someone that you are planning to use a Facade pattern instead of a MVC & they would instantly know the "structure" of what you plan to do. So you could directly get into a discussion about the merits/demerits of using a particular pattern & focus on what meets your business requirements rather than spend time explaining what you plan to do.

Note: The above statement is assuming that the "someone" also understood design patterns; else you can always point them out to this series for more information Tongue out

What is NOT a design pattern?

These are a few items that come to mind & I will keep updating this list if you have some more items to add here. So, here goes:

  • Design patterns are not architecture patterns - design patterns specifically deal with the problems at a software design (object creation, communication & behavior) level, while architecture patterns deal with the problems at the software engineering (communication, operation, maintenance, enviroment, physical/logical layers in the application) level
  • Design patterns are not solutions to your problem - design patterns are generic solutions to generic problems. Your application is not a generic application, so if you need to "customize" a design pattern to solve the specific problem you are facing. This customization would be valid only within the confines of your application to address that specific problem. You will need to start this analysis all over again in a different problem/project.
  • Design patterns are not algorithms - design patterns are not implementations, they are only a "framework" for a solution, while algorithms are implementation of a problem solutions to a problem. So, while algorithms may be directly used in your application (For example, an algorithm for a bubble sort), design patterns need to be tailored for your application
  • Design pattern is not a hammer looking for a nail
  • Design patterns are not answers looking for questions (this is a good quote from my friend & colleague Vasanth)

Why do I need design patterns?

Frankly, you could continue with the rest of your programming life without knowing a single design pattern & you could do just fine. As long as a piece of software meets its business goals, who cares what it does under the hood, really?

Then again, do you see a productivity benefit in using a proven development paradigm instead of re-inventing the wheel (unless the wheel was square, ofcourse)?

Would you prefer eliminating those hard to fix logical bugs in your application by using a standard template of avoiding such issues?

Do you like to appear cool (or a nerd, depending on the audience) by explaining the nuances of MVC/MVP patterns, or start a flame-war if MVC is really a design pattern or an architecture pattern?

If your answers to the above questions is a resounding YES, then unfortunately you do need to know what design patterns are.

On the bright side - you now have a new way to screw up your code & people might actually understand where you screwed up & help out with solutions!

Great, when do we start?

If you still didnot notice, we are already on our way!

This was the first of the series of articles & I hope to bring out the next one ASAP. Till then, you could go through my previous articles, which really have no connection to this article whatsoever, but interesting enough, I hope.

The Answer

Regading the answer I gave my colleague to his question posed at the start of this article, I realized that my colleague had two positives going in his favour:

  1. He realized that all software projects inherently had bugs/performance issues in them - to a detected or un-detected extent
  2. He was curious if his new-found knowledge could help him solve these issues
Since two positives still make a positive, I had replied: "Yeah, right!"

Currently rated 5.0 by 1 people

  • Currently 5/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Tags: , ,

Category: Design Patterns | Development