Java Singleton Design Pattern

Source: Internet
Author: User

From: http://www.javacoffeebreak.com/articles/designpatterns/index.html

For
Those who havent heard of design patterns before, or who are familiar
With the term but not its meaning, a design pattern is a template
Software development. The purpose of the template is to define a special behavior or technique that
Can be used as a building block for the construction of software-
Solve universal problems that commonly face developers. Think
Of design code as a way of passing on some nifty piece of advice, just
Like your mother used to give. "Never wear your socks for more
One day "might be an old family adage, passed down from generation
To generation. It's common sense solutions that are passed on to others.
Consider a design pattern as a useful piece of advice
Designing Software.

Design Patterns out of the way, let's look at the singleton. By now,
You're probably wondering what a singleton is-isn' t jargon terrible? A
Singleton is an object that cannot be instantiated. At first, that might
Seem counterintuitive-after all, we need an instance of an object
Before we can use it. Well yes a singleton can be created, but it can't
Be instantiated by developers-meaning that the singleton class has
Control over how it is created. The restriction on the Singleton is that
There can be only one instance of a singleton created by the Java
Virtual Machine (JVM)-by prevent direct instantiation we can ensure
That developers don't create a second copy.

So why wocould this be useful? Often in designing a system, we want
Control how an object is used, and prevent others (ourselves included) from making copies
Of it or creating new instances. For example, a central configuration
Object that stores setup information shoshould have one and one only
Instance-a global copy accessible from any part of the application,
Including any threads that are running. Creating a new configuration
Object and using it wocould be fairly useless, as other parts of
Application might be looking at the old configuration object, and
Changes to application settings wouldn't always be acted upon. I'm sure
You can think of a other situations where a singleton wocould be useful-
Perhaps you 've even used one before without giving it a name. It's
Common enough design criteria (not used everyday, but you'll come into your SS
It from time to time). The Singleton pattern can be applied in any
Language, but since we're all Java programmers here (if you're not,
Shame !) Let's look at how to implement the pattern using Java.

Preventing direct instantiation

We all know how objects are instantiated right? Maybe not everyone? Let's go
Through a quick refresher.

Objects are instantiated by usingnew
Keyword.new
Keyword allows you to create a new instance of an object, and to specify
Parameters to the class's constructor. You can specify no parameters, in
Which case the blank Constructor (also known asDefault
Constructor) is invoked. constructors can have access modifiers, like
Public and private, which allow you to control which classes have access
To a constructor. So to prevent direct instantiation, we create
Private default constructor, so that other classes can't create a new
Instance.

We'll start with the class definition, for a singletonobject class.
Next, we provide a default constructor that is marked as private. No
Actual code needs to be written, but you're free to add some
Initialization code if you 'd like.

public class SingletonObject
{
private SingletonObject()
{
// no code req'd
}
}

So far so good. But unless we add some further code, there'll be
Absolutely no way to use the class. We want to prevent direct
Instantiation, but we still need to allow a way to get a reference to
Instance of the singleton object.

Getting an instance of the singleton

We need to provide an accessor method, that returns an instance
The singletonobject class but doesn' t allow more than one copy to be
Accessed. We can manually instantiate an object, but we need to keep
Reference to the singleton so that subsequent callto the accessor
Method can return the singleton (rather than creating a new one). To Do
This, provide a public static method called getsingletonobject (), and
Store a copy of The Singleton in a private member variable.

public class SingletonObject
{
private SingletonObject()
{
// no code req'd
}

public static SingletonObject getSingletonObject()
{
if (ref == null)
// it's ok, we can call this constructor
ref = new SingletonObject();
return ref;
}

private static SingletonObject ref;
}

So far, so good. When first called, The getsingletonobject () method
Creates a singleton instance, assigns it to a member variable, and
Returns the singleton. Subsequent callwill return the same Singleton,
And all is well with the world. You cocould extend the functionality
The singleton object by adding new methods, to perform the types
Tasks your Singleton needs. So the Singleton is done, right? Well
Almost .....

Preventing thread problems with your Singleton

We need to make sure that threads calling the getsingletonobject ()
Method don't cause problems, so it's advisable to mark the method
Synchronized. This prevents two threads from calling
Getsingletonobject () method at the same time. If one thread entered
Method just after the other, you cocould end up calling
Singletonobject constructor twice and returning different values.
Change the method, just addsynchronized
Keyword
Follows to the method declaration :-

public static synchronized
SingletonObject getSingletonObject()

Are we finished yet?

There, finished. A singleton object that guarantees one instance
The class, and never more than one. Right? Well... not quite. Where
There's a will, there's a way-it is still possible to evade all our
Defensive Programming and create more than one instance of the singleton
Class defined above. Here's where most articles on singletons fall down,
Because they forget about cloning. Examine the following code snippet,
Which clones a singleton object.

public class Clone
{
public static void main(String args[])
throws Exception
{
// Get a singleton
SingletonObject obj =
SingletonObject.getSingletonObject();

// Buahahaha. Let's clone the object
SingletonObject clone =
(SingletonObject) obj.clone();
}
}

Okay, we're cheating a little here. There isn'tclone()
Method defined in singletonobject, but there is injava.lang.Object
Class which it is inherited from. By default,clone()
Method
Is marked as protected, but if your singletonobject extends another
Class that does support cloning, it is possible to violate the design
Principles of the singleton. So, to be absolutely positively 100%
Certain that a singleton really is a Singleton, we must addclone()
Method of our own, and throwCloneNotSupportedException
If anyone dares try!

Here's the final source code for a singletonobject, which you can use
As a template for your own singletons.

public class SingletonObject
{
private SingletonObject()
{
// no code req'd
}

public static SingletonObject getSingletonObject()
{
if (ref == null)
// it's ok, we can call this constructor
ref = new SingletonObject();
return ref;
}

public Object clone()
throws CloneNotSupportedException
{
throw new CloneNotSupportedException();
// that'll teach 'em
}

private static SingletonObject ref;
}
Summary

A singleton is an class that can be instantiated once, and only once.
This is a fairly unique property, but useful in a wide range of Object
Designs. Creating an implementation of the Singleton pattern is fairly
Straightforward-simple block off access to all constructors, provide
Static Method for getting an instance of the Singleton, and prevent
Cloning.

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.