Singleton Design Patterns Framework
          “Ensure a class only has once instance, and provide a global access point to it.”

The Singleton Pattern is a Creational pattern. In programming, you may need to make sure that there is only one instance of a class running. For example, a company’s email archiving system; it should be only one instance of an archiving class that handles all the archiving of all the company’s emails otherwise the same email would be archived more than once. This would result in redundant of effort, waist of time and space. Singleton Pattern is the answer to have only one instance of a class running and every process that needs such a class must use this Singleton instance.

One instance:
There are a number of issues that needed to be discussed on how to handle the creation and use of a Singleton Class. The following are some of them:
How to insure that there is only once instance?
How to prevent threading from a possible creation of more than one instance?
How to handle freeing the Singleton class?
Sub-Classing Singleton?
Casting
Servlets, Threading and Singleton
Cloneable, Class-Loaders, Remote Classes, Reflection, Serialization and Deserialization
How can we set a clear rule of communication between the developer who would create the Singleton class and the developer who would use (instantiate) the Singleton class?

How to insure that there is only once instance?
To insure there is only one instance, we need to keep the instantiation of the Singleton class private and not reachable except through one method. Therefore the Singleton class constructor should be declared private. We also need to create a private reference that handles the first and the only instance of the Singleton class. By doing that, we need to create a static method that would return the only existing instance of the Singleton class.

private static MySingleton instance;

/** Creates a new instance of MySingleton Constructor */
private MySingleton() {
}
/***************************/
private synchronized static void createAnInstance(){
          if(null == instance){
                    instance = new MySingleton();
                    System.out.println("A new MySingleton is created");
          }
}
/***************************/
public static MySingleton makeInstance(){
          if(null == instance)
                    createAnInstance();
          else
                    System.out.println("A copy of MySingleton is already created");
          return instance;
}

How to prevent threading from a possible creation of more than one instance?
To prevent a possible thread creation of more than one instance of the Singleton class, we need to create a “private synchronized static void” method that creates the Singleton class instance. This method when it is invoked, it would check for the existence of the Singleton class as following:

private synchronized static void createAnInstance(){
          if(null == instance){
                    instance = new MySingleton();
                    System.out.println("A new MySingleton is created");
          }
}

How to handle freeing the Singleton class?
Java does not provide a freeing method the same way C and C++ have, basically the developer sets the class reference to null and JVM garbage collector takes care of that at its convenience. Java “finalize()” method is the developer way of taking care of the house keeping when Java garbage collector would end an instance of the class. What ever code the developer places in the “finalize()” method will be executed when JVM garbage collector executes the “finalize()” method. The following is a way to insure that if the Singleton class is freed, then we do need to insure that it can be re-instantiated since the static reference to that class may still exist with incorrect reference and may not equal to null even after the class instance is freed. The following is an example of the “finalize()” method:

protected void finalize() {
          instance = null;
          try {
                    super.finalize();
          }
          catch(Throwable MyThrowable) {
                    System.out.println("finalize() catch clause");
          }
}

In the case of a Singleton class, we would need to insure that also the reference that exists within the Singleton class itself is not referencing to this Singleton class. To do that we set the private reference within the Singleton class to null and we place the in the “finalize()”.

Sub-Classing Singleton?
Multiple Singletons may be the result from when sub-classing a Singleton class. By setting the Singleton constructor as private that would prevent anyone from create another instance of the Singleton. A subclass could then declare a public constructor, allowing anyone to make instances. Since an instance of a subclass is an instance of its super-class also, that would arise multiple instances of the Singleton.

Casting:
Sub-classing may result in Multiple Singletons due to casting, where cast sub-class to parent class may allow the creation of the parent class.

Servlets, Threading and Singleton:
Servlets are threaded by design and having a servlet as a Singleton may results in Multiple Singletons. Also Threaded servlets may share its class variables (properties), but local variables within methods such as “doget()” or “doPost()” are created in each of the servlets threads and that may result in Multiple Singletons. Having the same Servlet runs on different server to distribute the load may result in Multiple Singletons.

Cloneable, Class-Loaders, Remote Classes, Reflection, Serialization and Deserialization
The main strength of Java is portability, and how Java code by run remotely on different platforms and sites. Such strength can also be a great disadvantage when come to Singleton classes. Cloning, Class-Loaders, Remote Classes, Reflection, Serialization and Deserialization would result in creation of more than one instance of Singleton class which defeats the main idea behind Singleton class.

Example of Singleton Class:
How can we set a clear rule of communication between the architect, the designer, the developer who would create the Singleton class (who we call him/her the Maker) and other developer (who we call the User) that would use (instantiate) the Singleton class?

To simplify communication between developers, we created two types of developers – Maker and User. Maker would be the developer who actual creates the code for the Singleton class and User would be the developer who would be using the Singleton class instance. We use Java interface for each to help set a common base of communication and rules for developing or using the Singleton class.

In MySingleton example, our attempt is limit the access of the Singleton class to specific user. So we created MySingletonUser interface and only MySingletonUser implementers can access the Singleton instance.

                                        MySingletonUser.java
                                        MySingleton.java
                                        User1_MySingleton.java

Rule of communication
The main ideal behind a Singleton is that there can be only one instance. Servlets, Sub-Classing, Casting, Cloning, Class-Loaders, Remote Classes, Reflection, Serialization and Deserialization would result in the creation of more than one instance of Singleton class. There should be a way of preventing the creation of multiple instance of a Singleton. It would be very difficult or almost impossible to do unless there are set rules for creating a Singleton class and such rules should force others to follow. This is our attempt to help with the issue of multiple instances of Singleton.

Singleton with a Key:
We created an interface call “Key” where it has a constant value and two methods called
“setKey()” and “getInstance()”. The developer who would instantiate the Singleton class must implement the Key interface.

public interface Key {
          int keyValue = 123;

          public void setKey();
          MySingletonWKey getInstance();
}

We designed the MySingletonWKey class so that both these methods must be invoked otherwise the MySingletonWKey class will return a null and print an error message.

                         setKey()
                         getInstance()

We basically set both the private constructor and the method that call the private instructor to return null if the key it not set. They also reset the key to “-1” so no one call create an instance or get a reference to the MySingletonWKey object. “The finalize()” also set the key to “-1” which enforces that both “setKey()” and “getInstance()” must be invoked to referece the Singleton instance.

We do need to stop at this point and check to see if our implementation of Mediator Pattern Design addresses the following concerns:
Thinking and approach
Set the Basis and Structure
Thinking and Approach:
Object Oriented Design (OOD) and thinking in OOD is the way to go. Looking our my_singleton_w_key Java Package example, we can see that we split the design into two parts:
Singleton
User(s)
Each part is a totally independent object and each one works independent of the rest. Each knows what rules to follow and what action to take. Each object can be developed by a Java developer. Each developer is free to do his tasks without any restrictions unless there are dependencies, where these dependencies can be temporary replaced with dummy values or messages.

Set the Basis and Structure:
In our Singleton Framework, we have two important methods that enforce the structure.

                    public void                                    setKey();
                    MySingletonWKey                     getInstance();

You can only access Singleton with a Key otherwise your get null for a reference.

Class Name Class Description
Key Interface:
The Key interface must be implemented by any Singleton User, where two methods must be overridden.
Key.java
Singleton WKey Class:
The actual implementation of Singleton class.
MySingletonWKey.java
User Class:
Used to test Singleton and its implementation
MySingletonUserWKey_java.html.java
Sub Singleton Class
Subbing of Singleton to test if it will be compiled.
SubMySingletonWKey.java