The Singleton Design Pattern and other Creational Patterns for Mobile

Creational Patterns

Perhaps you have felt like déjà vu when developing your web or mobile applications as you might have sensed that you are developing similar modules or routines that were already done in the past. Or you may have come up with a very similar solution from another application and you may  have been using a pattern and you did not know about it.

Today we will talk about “Design Patterns”, specifically about a particular pattern from the creational patterns category.

Every time we face a software design problem, we have to analyze the context to be able to provide a good solution. A design problem can be solved through many different ways and one of them is by making use of design patterns.

Design patterns help us to provide solutions for common software design problems, besides giving the capability to reuse our code and making it easy to maintain. There are three main categories known for design patterns:

  • - Creational
  • - Behavioral
  • - Structural

Creational Patterns

Creational patterns involve object instantiation and they all provide a way to decouple a client from the objects it needs to instantiate. The most common creational patterns are the following:

  • - Singleton
  • - Builder
  • - Prototype
  • - Abstract Factory
  • - Factory Method

We will cover a single pattern that is commonly used for software app development, the Singleton Pattern.

The Singleton Pattern

This is one of the simplest patterns, but really useful. It is the one that provides a single instance of an object. It might sound kind of weird to create just a SINGLE and UNIQUE instance of an object across all the web or mobile application context, but sometimes we do not need so many instances of an object because it is costly or difficult to manage them in certain scenarios.

Applicability

When shall we use the Singleton Pattern?

This is a good question. Before using a pattern, we have to make sure if it fits to the solution we are looking for. These are some scenarios where we can apply this particular pattern:

  • - Managing pools of resources: Connection and Thread pools

Eventually we have to establish a connection to a database, to select, create, update or delete records across the application logic. But what happens when we have to make so many calls that we have to open and close a connection every time we need to execute an action? We are wasting resources!

Why do not use just a simple connection pool to manage all the connections? Singleton to the rescue, this pattern is in charge of handling a single instance of an object that will be the single one to manage all the connections, in this way we can provide a connection pool that would be providing a certain number of connections and avoid opening and closing connections so frequently.

A similar scenario is present when we have to manage a set of threads.

  • - Managing global access: Reading a configuration file

It is common to load a configuration file for our web or mobile applications; it might be a properties file, an xml file, a json file, etc. Usually when we share the content of the configuration file across the entire application context, there is no need to load this file more than once, unless it changes frequently. A singleton class is useful for this scenario, since we avoid the loading of properties more than once every time a class needs to access that resource.

  • - Logging: Logger classes

When logging classes are created these have to provide a global logging access point in all the application components without being necessary to create an object each time a logging operation is performed. 

Singleton definition

The Singleton Pattern ensures that a class only has one instance, and provides a global point of access to it.

Singleton illustration

Singleton Design Pattern for Web App Development

 

Singleton characteristics

  • Ensures you have at most one instance of a class in your web or mobile app.
  • Provides a global access point to that instance.
  • Make use of a private constructor that prevents to be instantiated, a static method combined with a static variable.

Singleton is used by other patterns like: Abstract Factory, Builder, Prototype, Facade, etc.

When we are sure that at least one instance will be needed, we can use the following sample of the Singleton Pattern implementation in Java.

Code snippet:

<strong>public</strong> <strong>class</strong> MySingleton {
   <strong>private</strong> <strong>static</strong> <strong>final</strong> MySingleton INSTANCE = <strong>new</strong> MySingleton();
   <strong>private</strong> MySingleton() {}
   <strong>public</strong> <strong>static</strong> MySingleton getInstance() {
       <strong>return</strong> INSTANCE;
   }
}

On the other hand, when the initialization process is costly, then we can use the lazy initialization:

Code snippet:

public class MySingleton {
   private static final MySingleton INSTANCE = null;

   private MySingleton() {}

   public static MySingleton getInstance() {

if(INSTANCE ==null){
   INSTANCE = <strong>new</strong> MySingleton();
}
      return INSTANCE;
   }
}

A problem that we might face when using lazy initialization is that if two different threads try to get an instance at the same time they might end up with two different objects because the getInstance method is not synchronized.

If you  have any questions don't forget to submit your comments and let us know if there's something else you'd like us to talk about! Happy coding!

About the Author

Armando H. holds a Bachelor in System Engineering with 7+ years of experience in Software Development using Java as his main technology. He is currently working at iTexico as a Software Developer for Web Applications.

Oscar Salas

Written by Oscar Salas

Oscar Salas is a B2B Digital Marketing Specialist with 5 years of experience, who has helped organizations to grow and expand through strategic brand development and marketing programs. Analytical thinker, cat lover, he enjoys to play the piano and listening to Led Zeppelin He's currently leading the iTexico Demand Gen strategies.

Explore iTexico, The Nearshore + Company 

Explore The Nearshore Services

Read More

Mobile Competency Center

Recent Posts