Follow treslines by email clicking Here!

Tuesday, August 12, 2014

Programming Design Pattern - Singleton Pattern Applied - Best Practise

Hi there!

Today i'm gonna show the singleton design pattern in action. The singleton design pattern is a largely used and common programming design pattern while dealing with uniqueness in your application.

I'm assuming here you already know the concepts and i'll be focusing on practise. The example i will provide is a nice way to show it how it could looks like. You can always come back here, take it, adapt it and use it in your applictions as you may need. So be sure you bookmark it or join the group here on the right side of this post subscribing it.

First of all, let's take a look at the UML diagram of it. After that we will take the analogy for our example.

The simpliest UML - Singleton Pattern


Pay close attention, because once you understand that, everything will become clear and simple to understand. That's the reason I'm putting always the UML first. That way you'll get an eye for it with the time.

The Singleton

This is a very common design pattern and largely used with most applications out there. It's important to know this pattern, because you'll see it a lot of times during your programming life. There are, so far as i know, four categories of singletons. Synchronized, not synchronized, lazy, and not lazy initialized. The way you can construct it is largely discussed. You may use an enum or a normal class. In the example bellow i used a normal class.

public final class Session 
{
    private static Session instance;
    /** singleton */
    private Session() {}
    /** if you do not need synchronization do not mark it as synchronized */
    public synchronized static Session getInstance() 
    {
        return (instance == null) ? instance = new Session() : instance;
    }
    /** your methods goes here... */
 }

That's all! Hope you like it!

No comments:

Post a Comment