Applying design Patterns in Java--singleton

Source: Internet
Author: User
Tags object constructor getmessage implement string static class variable access
Design This paper introduces the basic concept of Singleton in design pattern, analyzes its function and usage, lists several methods that usually implement Singleton, and gives detailed Java code.

Basic concepts

Singleton is a creation model that is used to ensure that only one instance is generated and provides a global access point to access it. For some classes, it is important to ensure that only one instance is available, such as when a database connection or Socket connection is limited to a certain extent, There must be only one connection at the same time. For example, a set in a set cannot contain duplicate elements, and an object added to a set must be unique, and if a duplicate value is added to set, it accepts only one instance. The singleton mode is formally used in the JDK to implement this feature of set. You can view the original code of the internal static class Singletonset in Java.util.Collections. In fact, Singleton is one of the simplest but most widely used models, and is ubiquitous in the JDK.

Simple analysis

In order to implement the Singleton pattern, we need a static variable that can remember whether an instance has been created without creating an object. Static or static methods can be called directly without producing a specific instance. Such a variable or method will not change because of the instantiation of the class. As you can see in the structure of Figure 1, Uniqueinstance is the independent static variable that can remember whether an object has been instantiated and judge the variable in a static method Instance If no instantiation occurs, a new object is generated, and if it is already instantiated, the new object is no longer generated and still returns the previously generated instance.


Figure 1:singleton Pattern Structure

Specific implementation

There are usually three ways to implement the Singleton model.

A. Using static method to realize Singleton

This method uses a static method to monitor the creation of instances. To prevent more than one instance from being created, we'd better declare the constructor private.

This prevents the client programmer from creating an instance in any way other than the one provided by us, and if the constructor is not declared private, the compiler will be smart to automatically synchronize a default friendly constructor. This implementation is the most common, This is the standard implementation of the structure in Figure 1.

public class Singleton {
private static Singleton s;
Private Singleton () {};
/**
* Class method to access the singleton instance of the class.
*/
public static Singleton getinstance () {
if (s = = null)
s = new Singleton ();
return s;
}
}

Test class
Class Singletontest {
public static void Main (string[] args) {
Singleton S1 = singleton.getinstance ();
Singleton s2 = singleton.getinstance ();
if (S1==S2)
System.out.println ("S1 is the same instance with S2");
Else
System.out.println ("S1 is not the same instance with S2");
}
}

Singletontest Run results are:
S1 is the same instance with S2
This proves that we have only created one instance.

Two. Implement Singleton with static variable as symbol

Embedding a static variable as a flag in a class is checked every time it enters the constructor.

The problem is that the constructor does not have a return type, if it is determined that the creation of an instance is successful or not. One method is to call a function to check whether the creation was successful, and then simply return a value from a static variable, but this is not elegant, And it's easy to make mistakes. It's a good idea to create a class that throws an exception when more than one instance is created, a class that simply invokes the parent class method, with the exception type named and the error message clearer:

Class Singletonexception extends RuntimeException {
Public Singletonexception (String s) {
Super (s);
}
}

Class Singleton {
static Boolean instance_flag = false; True if 1 instance
Public Singleton () {
if (Instance_flag)
throw new Singletonexception ("Only one instance allowed");
Else
Instance_flag = true; Set flag for 1 instance
}
}

Test class

public class Singletontest {
static public void Main (String argv[]) {
Singleton S1, S2;
Create one incetance--this should always work
SYSTEM.OUT.PRINTLN ("Creating one instance");
try {
S1 = new Singleton ();
catch (Singletonexception e) {
System.out.println (E.getmessage ());
}
Try to create another spooler--should fail
SYSTEM.OUT.PRINTLN ("Creating two instance");
try {
S2 = new Singleton ();
catch (Singletonexception e) {
System.out.println (E.getmessage ());
}
}
}

Singletontest Run results are:
Creating one instance
Creating two instance
Only one instance allowed
As you can see, the first instance is created successfully, and the second instance creates a real throw of our custom exception.

Three. Use the Registrar mechanism to create Singleton

First, the Hashtable and enumeration in the set are used to implement AddItem (object key, Object value), GetItem (Object key), RemoveItem (object key) The method implements a manager that associates key with value one by one, and the client programmer first registers with the AddItem method before creating the instance, and then obtains the instance using the GetItem method. The key in Hashtable is unique, guaranteeing that the instance created is unique, Specific implementation is limited to space no longer detailed, in the application of prototype model I will give a code to implement the Registrar. The benefit of creating a singleton pattern with the registrar mechanism is that it is easy to manage and can control multiple different types of singleton instances at the same time.

Summary

1. The singleton model can be easily expanded to produce a specified number of instances.

2. In the design Patterns Java Companion, it has been mentioned that using static classes to implement singleton patterns, and that Java.lang.Math is an example, I do not agree Since math is not a real object, we simply call the static method that the math class wraps, and there is no process of creating an instance, and where does it come from? I have posted a post on the Javaranch forum, All the people who have replies are also negative about this view.

3. In multithreaded programs, Singleton may become unreliable, multiple instances may appear, the solution is simple, add a synchronization modifier: public static synchronized Singleton getinstance (). This guarantees the security of the thread.

4. Finally, you may see some other ways to achieve singleton mode, because the pattern in the specific application is flexible, not static, and do not have a fixed approach, but most of the above are the deformation of several methods.


Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.