Singleton pattern used when we want to allow only a single instance of a class can be created inside our application. Using this pattern ensures that a class only have a single instance by protecting the class creation process, by setting the class constructor into private access modifier.
To get the class instance, the singleton class can provide a method for example a getInstance() method, this will be the only method that can be accessed to get the instance.
01.
package
new.mypack.sample
02.
03.
public
class
Service {
04.
private
static
Service instance =
new
Service();
05.
06.
private
Service() {
07.
}
08.
09.
public
static
synchronized
Service getInstance() {
10.
return
instance;
11.
}
12.
13.
@Override
14.
protected
Object clone()
throws
CloneNotSupportedException {
15.
throw
new
CloneNotSupportedException(
"Clone is not allowed."
);
16.
}
17.
}
There are some rules that need to be followed when we want to implement a singleton.
- From the example code above you can see that a singleton has a static variable to keep it sole instance.
- You need to set the class constructor into private access modifier. By this you will not allowed any other class to create an instance of this singleton because they have no access to the constructor.
- Because no other class can instantiate this singleton how can we use it? the answer is the singleton should provide a service to it users by providing some method that returns the instance, for example getInstance().
- When we use our singleton in a multi threaded application we need to make sure that instance creation process not resulting more that one instance, so we add a synchronized keywords to protect more than one thread access this method at the same time.
- It is also advisable to override the
clone()
method of thejava.lang.Object
class and throwCloneNotSupportedException
so that another instance cannot be created by cloning the singleton object.
No comments:
Post a Comment