Wednesday, October 7, 2015

Singleton Pattern

This is one of the simplest, yet very useful design pattern. Singleton design pattern can be used when it is required to create just one object of a class. As an example, if you have a ApplicationManager class in your application where all other components need to get help from, you need to have access to ApplicationManager object. But just think that you need to share some objects through your ApplicationManager. Then of course you do not want to have different object referring to different ApplicationManager objects. You need to have one common object shared with all of them. And singleton pattern is the way to achieve this.

I believe an example code snippet will help a lot in understanding this simply.


public class ApplicationManager {

    private static ApplicationManager applicationManager = new ApplicationManager();

    private ApplicationManager() { }

    public static ApplicationManager getInstance() {
        return applicationManager;
    }
    
    public void yourMethod() {
        //code
    }
}


So you see the constructor is private, so no one can initialize an object of ApplicationManager and if they want to use it, can call getInstance() method and use the already created static ApplicationManager object. So no more than one object is created and global access is provided.

6 comments:

  1. Singleton pattern is helping to design the software and mostly software engineers are using this pattern to design. Singleton pattern code is not difficult I am also read this subject and also design software with the help of this.

    ReplyDelete
  2. Sickbits - Sickbits is a library of unlimited hacks for android, ios smartphones. Get unlimited amount of hacks and modes for mac & pc.
    Livehacx - livehacx is a hub of unlimited cracked and latest software which you can download. Install latest softwares on your MacBook and Windows laptops.

    ReplyDelete
  3. I like viewing web sites which comprehend the price of delivering the excellent useful resource free of charge. I truly adored reading your posting. Thank you!
    madalin stunt cars 2

    ReplyDelete
  4. Cracks.live
    Download latest cracks of mac & pc softwares. You can get full versions of latest games, softwares, applications and many tools. Spectrasonics Omnisphere Crack With Serial Key

    ReplyDelete