JAVA How to JAVA Development tutorials and how to

2May/100

JAVA Singleton Pattern

Singleton Pattern - JAVA How to

Hello again, after 3 weeks of posts absense, i'm back 8-) . Back with JAVA design patterns stuff, this time about How to apply Singleton Pattern, basically a pattern that allows you to restrict to instantiate more than one instance of a class in your application. The requirements that you satisfy with Singleton Pattern are:

  • Only one instance of a class per application
  • If you try to instantiate a second object from singleton class, you'll get the original instance

I decided to write about it because i had a requirement in a project where i'm working right now that involves to handle an object to mantain the user state and other data in a single object, without possibility of instantiate another one and access easily to current object, so i decided to implement the pattern. First, you need to restrict the constructor of the class to avoid to instantiate object in the usual way so we have to declare the constructor as private. next you have to declare a method that, if an object isn't created yet, instantiate a new object and returns it, or, if object is already created, return a reference to that object...