Jump to content
Sign in to follow this  

[Tutorial] Singleton Pattern

Recommended Posts

Hi, I'm just posting this tutorial for people who want to structure their application in a cleaner more environmentally friendly way.

A lot of people tend to static variables which is not terrible but if it can be avoided, it should be also I've seen some code that creates a new object for every class when they only need one instance of it which the Singleton Pattern takes care of.

The singleton pattern restricts instantiation of a class to ONE object. This is useful if you need to use an object in every one of your classes like a Variables object but don't want to keep creating a new object every time.

It's fairly simple to implement.


It basically takes advantage of a private constructor. So to create an object it has to be done inside the class which is done by the method getInstance(); Also it is synchronized and therefore thread-safe of course.

To get the instance simply call

Singleton singleton = Singleton.getInstance();

On the first call it will instantiate the object, and every other call it will simply return the instance that was already instantiated.

For more info: https://en.wikipedia.org/wiki/Singleton_pattern

The wikipedia page shows different ways you can implement the singleton pattern.


  • Like 2

Share this post

Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this  

  • Recently Browsing   0 members

    No registered users viewing this page.