Code like a Pro | Courtesy: blogs.warwick.ac.uk

We all know how important design patterns are, right? Well Just to bring you to perspective. Imagine, you compiled a code of say 10,000 lines without any definite structure. How difficult would it be for you to modify & restructure the code if required. Even if someone else wants to work on your code if would be a challenge without a definite Blue Print.

Design Patterns are nothing but this blue print & are a popular topic in software development arena. A design pattern is a common, well-described solution to a common software problem. So the sensible use of the right design patterns can result in not only increased code maintainability, design patterns can also be recognized by other developers, thus reducing the learning curve when dealing with a particular piece of code.

 

 

So what are these Design Patterns? Let’s Jump right in !!

design pattern describes the classes and interacting objects used to solve a general design problem in a specific context.

There are many design patterns available, some of the important ones that we will be discussing are:

1.Singleton Pattern
2.Decorator Pattern
3.Factory Pattern
4.Abstract Factory Pattern

So let us start with the Singleton Pattern & cover the common know hows on how to implement it.

Definition: The Singleton pattern ensures that a class has only one instance and provide a global point of access to that instance. It is named after the singleton set, which is defined to be a set containing one element.

An Example would be the office of the President of India, it’s is a Singleton. The Indian Constitution specifies the means by which a president is elected, limit the term of office and defines the order of succession. As a result, there can be at most one active President at any given time. Regardless of the personal identity of the active President, the title “The President of India” is a global point of access that identifies the person in the office.

 

Why do we use these Singleton Patterns?

  • In Singleton, it takes care that a class only has one instance and provides the global access for it. It encapsulated on the first use.
  • It speeds up the development process by providing a tested, proven development paradigm. It  also improves code readability for coders and architects who are familiar with these patterns.
  • Singleton Design patterns provide general solutions, documented in a format that does not require specifics tied to the particular problem.

Here are some real situations where the singleton is used:

  1. Logger Classes:  Singleton Design patterns help in designing logger classes. In this class, it creates the global access point to use logger operations.
  2. Configuration Classes: Singleton patterns are useful in creation of configuration object and can be keep it in cache. This avoids the reloading of data and also avoids the open and close operations with the system.
  3. Accessing shared resources: In multi-threading application Singleton plays an important role. Many threads are accessed by the same method and the result is updated; in this case Singleton can perform better holding of the global access point.

 

How to use a Singleton J2EE Environment for the Creations of Heavy Database Instances?

How to Construct a Singleton

Nowadays Java web applications use ORM (Object Relational Mapping)  for database like Hibernate. In Hibernate as you know, SessionFactory is a long live multi threaded object. Usually one session factory should be created for one database. If you assume the scenario that you are using one database called mysql in your application then the following is a way to create the SessionFactory object, the java code snippets are:

 

public class HibernateUtil {
	private static final SessionFactory sessionFactory;
	static {
		try {
			sessionFactory = new Configuration().configure()
					.buildSessionFactory();
		} catch (Throwable ex) {
			System.err.println("Initial SessionFactory creation failed." + ex);
			throw new ExceptionInInitializerError(ex);
		}
	}

	public static SessionFactory getSessionFactory() {
		return sessionFactory;
	}
}

When we are use more than one database in our application then we use the HibernateUtil class which is implemented based on singleton design pattern, which insures that one and only one SessionFactory object will be created for the entire application.

 

How would we use Singleton in a Mobile Application Development?

Usually in mobile, many applications run concurrently in the screen stack or in the background. Mobile operating systems do not support large databases like Oracle, Mysql etc. instead it supports light weight databases e.g., SQLite. The reason is the issue of memory. Suppose one application is running on screen which stores the user data in the database(SQLite) and there are four applications that are running in the background which updates some data when a particular event occurs.  In this case all applications can be woken up on the same time and this will create many instances of the database which is expensive and results may be OutOfMemory or StackOverFlow! If you use a Singleton multithreaded database instance however, you can run apps smoothly. Following is an Android code snippet which uses Singleton:

public class DatabaseHelper extends SQLiteOpenHelper { 

  private static DatabaseHelper sInstance;

  private static final String DATABASE_NAME = "database_name";
  private static final String DATABASE_TABLE = "table_name";
  private static final int DATABASE_VERSION = 1;

  public static DatabaseHelper getInstance(Context context) {

    // Use the application context, which will ensure that you 
    // don't accidentally leak an Activity's context.
    // See this article for more information: https://bit.ly/6LRzfx
    if (sInstance == null) {
      sInstance = new DatabaseHelper(context.getApplicationContext());
    }
    return sInstance;
  }

  /**
   * Constructor should be private to prevent direct instantiation.
   * make call to static factory method "getInstance()" instead.
   */
  private DatabaseHelper(Context context) {
    super(context, DATABASE_NAME, null, DATABASE_VERSION);
  }
}

 

So when Should You NOT use a Singleton Approach?

Reality check, Singleton patterns are one of the most inappropriately used patterns in today’s world. Most of the programmers use it for replacing the global variable idea because of misguidance. The real problem with the Singleton approach is that they give you a good excuse not to think carefully about the appropriate visibility of an object. So think before you choose your design pattern so that your Code works efficiently!

Singletons are also bad when it comes to clustering. Because then, you do not have “exactly one singleton” in your application anymore. Let’s check this out.

Consider the following situation: As a developer, you have to create a web application which accesses a database. To ensure that concurrent database calls do not conflict each other, you create a thread-save SingletonDao as follows:

public class SingletonDao {
    // songleton's static variable and getInstance() method etc. omitted
    public void writeXYZ(...){
        synchronized(...){
            // some database writing operations...
        }
    }
}

So you are sure that only one singleton in your application exists and all databases go through this one and only SingletonDao. Your production environment now looks like this:

 

One Singleton in your App

Now, consider you want to set up multiple instances of your web application in a cluster. You suddenly have something like this now:

 

Multiple Instances of your Web App

 

So you have many singletons in your application. And that is exactly what a singleton is not supposed to be: Having many objects of it. This is especially bad if you, as shown in this example, want to make synchronized calls to a database. But the message of this example is: You can not rely that there is exactly one instance of a singleton in your application – especially when it comes to clustering.

So Singleton is not applicable here. What can you use instead? You can solve this by creating different instances of  the database and can be use database connection pooling to control the number of instances. You can  also use the Factory Pattern (which we will discuss in our later blogs) which creates a different component of databases (You should off-course provide database pooling).

Stay tuned for more Design Patterns coming your way here! Subscribe to our Blogs to know more about Design Patterns & Other Tech Know-Hows!

Tags: , , , ,