When I want to reuse a Singleton pattern by using inheriting in Java language, something interesting confused me. I want share with you and ask you for a solution to reuse Singleton.
My code is below.
// Singleton.java
public class Singleton {
private static Singleton mSingletonInstance;
protected Singleton() {
System.out.println("New Singleton Instance.");
}
public static Singleton getInstance() {
if (mSingletonInstance == null)
mSingletonInstance = new Singleton();
return mSingletonInstance;
}
}
// ExtendedSingleton.java
public class ExtendedSingleton extends Singleton{
private static ExtendedSingleton mExtendedSingleton;
private ExtendedSingleton() {
super();
System.out.println("New Extended Singleton Instance.");
}
public static ExtendedSingleton getInstance() {
if (mExtendedSingleton == null)
mExtendedSingleton = new ExtendedSingleton();
return mExtendedSingleton;
}
public static void main(String args[]) {
ExtendedSingleton extendedSingleton = ExtendedSingleton.getInstance();
}
}
Of course, I can run these code without any exception. But my intention is to reuse the Singleton pattern by extending a Singleton base class. However, I have to retype all of the code in the subclass and I didn't reuse anything at all, which is even not better that write a separate Singleton class whenever I need it. I am really confused. Could anyone show me how to reuse the Singleton pattern.
Feel free to fix my English, which I know I must have a lot of mistakes.
I would just use an enum if you want to use the features of Java. Your classes would look like
enum Singleton {
INSTANCE;
// add fields and methods to taste
}
enum ExtendedSingleton {
INSTANCE;
// delegate to Singleton as required.
}
If you need inheritance, you can use an interface which they both implement.
Singleton pattern assumes a private constructor. You break this rule this is why the confusion. Do not extend it
Related
I am developing a design pattern, and I want to make sure that here is just one instance of a class in Java Virtual Machine, to funnel all requests for some resource through a single point, but I don't know if it is possible.
I can only think of a way to count instances of a class and destroy all instance after first is created.
Is this a right approach? If not, is there any other way?
Use the singleton pattern. The easiest implementation consists of a private constructor and a field to hold its result, and a static accessor method with a name like getInstance().
The private field can be assigned from within a static initializer block or, more simply, using an initializer. The getInstance() method (which must be public) then simply returns this instance,
public class Singleton {
private static Singleton instance;
/**
* A private Constructor prevents any other class from
* instantiating.
*/
private Singleton() {
// nothing to do this time
}
/**
* The Static initializer constructs the instance at class
* loading time; this is to simulate a more involved
* construction process (it it were really simple, you'd just
* use an initializer)
*/
static {
instance = new Singleton();
}
/** Static 'instance' method */
public static Singleton getInstance() {
return instance;
}
// other methods protected by singleton-ness would be here...
/** A simple demo method */
public String demoMethod() {
return "demo";
}
}
Note that the method of using “lazy evaluation” in the getInstance() method (which
is advocated in Design Patterns), is not necessary in Java because Java already uses “lazy
loading.” Your singleton class will probably not get loaded unless its getInstance()
is called, so there is no point in trying to defer the singleton construction until it’s needed
by having getInstance() test the singleton variable for null and creating the singleton
there.
Using this class is equally simple: simply get and retain the reference, and invoke methods on it:
public class SingletonDemo {
public static void main(String[] args) {
Singleton tmp = Singleton.getInstance();
tmp.demoMethod();
}
}
Some commentators believe that a singleton should also provide a public final
clone() method that just throws an exception, to avoid subclasses that “cheat” and
clone() the singleton. However, it is clear that a class with only a private constructor
cannot be subclassed, so this paranoia does not appear to be necessary.
That's the well known Singleton pattern: you can implement this as follows:
public class SingletonClass {
//this field contains the single instance every initialized.
private static final instance = new SingletonClass();
//constructor *must* be private, otherwise other classes can make an instance as well
private SingletonClass () {
//initialize
}
//this is the method to obtain the single instance
public static SingletonClass getInstance () {
return instance;
}
}
You then call for the instance (like you would constructing a non-singleton) with:
SingletonClass.getInstance();
But in literature, a Singleton is in general considered to be a bad design idea. Of course this always somewhat depends on the situation, but most programmers advice against it. Only saying it, don't shoot on the messenger...
There is a school of thought that considers the Singleton pattern to in fact be an anti-pattern.
Considering a class A that you only wish to have one of, then an alternative is to have a builder or factory class that itself limits the creation of the number of objects of Class A, and that could be by a simple counter.
The advantage is that Class A no longer needs to worry about that, it concentrates on its real purpose. Every class that uses it no longer has to worry about it being a singleton either (no more getInstance() calls).
You want the Singleton pattern. There is an excellent discussion of how to implement this properly. If you do this right, there will only ever be one instance of the class.
Essentially what you are going to do is create a class, hold a single instantiated object of that class at the static level, and provide a static accessor to get it (getInstance() or similar). Make the constructor final so people can't create their own instances out of the blue. That link above has plenty of great advice on how to do this.
Use enum. In Java enum is the only true way to create a singleton. Private constructors can be still called through reflection.
See this StackOverflow question for more details:
Implementing Singleton with an Enum (in Java)
Discussion:
http://javarevisited.blogspot.com/2012/07/why-enum-singleton-are-better-in-java.html
I can only think of a way to count instances of a class and destroy all instance after first is created. Is this a right approach ? If not, is there any other way ?
The correct technical approach is to declare all of the constructors for the class as private so that instances of the class can only be created by the class itself. Then you code the class only ever create one instance.
Other Answers show some of the ways to implement this, according to the "Singleton" design pattern. However, implementing a singleton like this has some drawbacks, including making it significantly harder to write unit tests.
I prefer lazy singleton class, which overrides readResolve method.
For Serializable and Externalizable classes, the readResolve method allows a class to replace/resolve the object read from the stream before it is returned to the caller. By implementing the readResolve method, a class can directly control the types and instances of its own instances being deserialized.
Lazy singleton using /Initialization-on-demand_holder_idiom:
public final class LazySingleton {
private LazySingleton() {}
public static LazySingleton getInstance() {
return LazyHolder.INSTANCE;
}
private static class LazyHolder {
private static final LazySingleton INSTANCE = new LazySingleton();
}
private Object readResolve() {
return LazyHolder.INSTANCE;
}
}
Key notes:
final keyword prohibits extension of this class by sub-classing
private constructor prohibits direct object creation with new operator in caller classes
readResolve prohibits creation of multiple instances of class during object de-serialization
For that you need to use singleton pattern, I am just posting a demo code for that that may useful for your understanding.
E.g: If I want only one object for this Connect class:
public final class Connect {
private Connect() {}
private volatile static Connect connect = null;
public static Connect getinstance() {
if(connect == null) {
synchronized (Connect.class) {
connect = new Connect();
}
}
return connect;
}
}
Here the constructor is private, so no one can use new keyword to make a new instance.
class A{
private A(){
}
public static A creator(A obj){
A ob=new A();
return ob;
}
void test(){
System.out.println("The method is called");
}
}
class Demo{
public static void main(String[] args){
A ob=null;
ob=A.creator(ob);
ob.test();
}
}
What is the purpose of getInstance() in Java?
During my research I keep reading that getInstance() helps achieve a Singleton design pattern (which means just one instance across the whole program to my understanding). But can't I just use static? Isn't that the whole point of static?
If I were to just have static methods and fields, how would it differ from using getInstance()? Is there a "scope" of static? For example, one instance per method or class?
And if they are different, in what cases would I choose getInstance() over using static?
I apologize if the question is unclear, I am sure I am missing something on the subject matter, I just can't figure out what.
Thank you for any and all advice.
Static will not give you a singleton. Since there is no way of making a top-level class a singleton in Java, you have getInstance methods which will implement some logic to to be sure there is only one instance of a class.
public class Singleton {
private static Singleton singleton;
private Singleton(){ }
public static synchronized Singleton getInstance( ) {
if (singleton == null)
singleton=new Singleton();
return singleton;
}
}
Check out this top answer: Static Classes In Java
The above code will allow only one instance to be created, and it's clean, however as of Java 1.6, it is better to create singleton's as such since it is slightly more elegant IMHO:
public enum MyEnumSingleton {
INSTANCE;
// other useful methods here
}
Source: http://www.vogella.com/tutorials/DesignPatternSingleton/article.html
Singleton
A singleton allows you to use a single reference to a java Object. For example, here is a singleton which contains a number;
public class MySingleton {
private int myNumber;
private static MySingleton instance;
public static MySingleton getInstance() {
if (instance == null) {
instance = new MySingleton();
}
return instance;
}
private MySingleton() {}
public void setMyNumber(int myNumber) {
this.myNumber = myNumber;
}
public int getMyNumber() {
return myNumber;
}
}
Now we are going to set the value of this number in the A class:
public class A {
/*...*/
MySingleton mySingleton = MySingleton.getInstance();
mySingleton.setMyNumber(42);
/*...*/
}
Then, you can access this value from another class:
public class B {
/*...*/
MySingleton mySingleton = MySingleton.getInstance();
int number = mySingleton.getMyNumber();
/*...*/
}
In this class the number variable will have the value 42. This is the advantage of a singleton over a simple object:
All the values stored in the singleton will be accessible from
"everywhere".
Static class
The purpose is different, here the advantage is to use an object without having to create it.
For example:
public static class MyStaticClass {
public static void sayHello() {
System.out.println("Hello");
}
}
Now you can use the sayHello() method from any classes by calling:
MyStaticClass.sayHello();
The exact method of implementing a singleton, for example using a factory method called getInstance(), isn't that relevant to the question, which is "static methods vs singleton with instance methods".
Classes are themselves effectively singletons, so from that aspect they are similar.
The main difference is that static methods are not part of class hierarchy - they are not inherited, which means the static method option locks you forever to using that exact class and it can't be referred to in any other way, such being an implementation of some interface or a super class.
Instances however don't have this problem, so you can code for example:
class MySingleton implements SomeInterface {
...
}
SomeInterface instance = MySingleton.getInstance();
I prefer to use static too, but sometimes getInstance() is helpful to have some functions that will be related to the object, in which you can modify variables. if you are simply making some util functions that do not need an instance of an object, use static.
When you are using someone's libraries, you never know if a function body needs a class instance. That's why a lot of library classes are using getInstance().
Instead of checking for null, I like this a little better.
public class SingleObject {
//create an object of SingleObject
private static SingleObject instance = new SingleObject();
//make the constructor private so that this class cannot be
//instantiated
private SingleObject(){}
//Get the only object available
public static SingleObject getInstance(){
return instance;
}
}
Called with...
public class SingletonPatternDemo {
public static void main(String[] args) {
//illegal construct
//Compile Time Error: The constructor SingleObject() is not visible
//SingleObject object = new SingleObject();
//Get the only object available
SingleObject object = SingleObject.getInstance();
}
}
Full code from: http://www.tutorialspoint.com/design_pattern/singleton_pattern.htm
One overlooked reason to use a singleton instead of static class member variables is that the static member variables MAY use space and garbage collector time even in the event the class is never instantiated. Consider how many classes are available to you in rt.jar and what a small fraction of them you probably use in any given application. Also consider that using getInstance ensures your "constructor" has run before any of the member variables are accessed. I almost universally see getInstance as synchronized but I feel this is a bad idea. If anyone ever adds a synchronized blocking method calls to Singleton.getInstance().unsynchronized() could be needlessly held up.
private static Singleton instance = null;
private Singleton() {}
public final static Singleton getInstance() {
return (instance != null) ? instance : makeInstance();
}
private final static synchronized Singleton makeInstance() {
return ( instance != null ) ? instance : ( instance = new Singleton() );
}
I searched but didn't find any normal information for Java Singleton functions or classes , So can anybody explain why I need them? What is he difference from other functions?
Singleton pattern is used for classes that should only exist by one instance. The purpose of the singleton and its values should be consistent throughout the entire application.
Singletons are commonly used for special environment variables, database connections, factories and object pools.
Singleton is used to create only one instance of the Object
public class Singleton {
private static Singleton uniqueInstance;
// other stuff
private Singleton()
{
}
public static Singleton getInstance()
{
if(uniqueInstance == null)
{
uniqueInstance = new Singleton();
}
return uniqueInstance;
}
// other methods
}
This is the simple example to make you aware og the singleton pattern
Sometimes it's appropriate to have exactly one instance of a class: window managers, print spoolers, and filesystems are prototypical examples. Typically, those types of objects—known as Singletons
There is nothing like Singleton function , we usually use Singleton Classes
http://www.javapractices.com/topic/TopicAction.do?Id=46
ok this classes has only one object. for making a class Singleton, make the constructor private and define a static method to get the class object like this
public class yourclassname{
private yourclassname{}
public static yourclassname getMySongAlarmdb(Context c)
{
if (myobject == null){
myobject = new yourclassname;
}
return myobject;
}
}
Does making the below class final (adding public final class) have any real impact on this classes intent to implement the singleton pattern?
package org.kodejava.example.pattern.factory;
public class Singleton {
private static Singleton instance = new Singleton();
private Singleton() {
}
public static synchronized Singleton getInstance() {
return instance;
}
public void doSomething() {
for (int i = 0; i < 10; i++) {
System.out.println("i = " + i);
}
}
#Override
protected Object clone() throws CloneNotSupportedException {
throw new CloneNotSupportedException("Clone is not allowed.");
}
}
No, not really. As the constructor is private it cannot be subclassed anyway. It just makes the fact more explicit, which is why I'd use final personally.
When you create a singleton, you try by all means to enforce the pattern. That means, there should be no ways whatsoever to create a second instance of the singleton class.
By declaring a private constructor you ensure no other top level class can extend your Singleton class, but an inner class or static inner class could extend it and break your singleton because an inner class have access to the private members of its enclosing class.
Evidently, this could not happen unless you really wanted it so, but, yet again, if you want to make your singleton bullet proof, if you declare it final, you could be preventing, by all means possible, that the pattern is broken.
Please see this,
When you do this:
private static Singleton instance = new Singleton();
ie. initializing the object during declaration in your above code.
then, there is no need to use synchronized on the getInstance() method, Dont worry. still singleton is implemented with 100% assurance.
just do this:
public static Singleton getInstance() {
return instance;
}
Final keyword will just make sure that the class can Not be extended..thats it.. It Will Not effect the singleton pattern.
You can use the Double Check Locking also to implement Singleton Pattern, Please refer HEAD FIRST DESIGN PATTERN
No. Class is already singleton pattern. Final modifier makes class non-derivable but it is already non-derivable as it has private constructor.
This is my singleton class for obtaining the database connection.
I have a question here: why it compulsory to have a private constructor inside a singleton class (as throughout my entire application I am calling this class only once) and as one instance of a class can be achieved using the static method?
Can this private constructor can be avoided, or is it mantadatory?
public class ConnPoolFactory {
private static DataSource dataSource;
private static Connection connection;
private ConnPoolFactory() {
System.out.println(" ConnPoolFactory cons is called ");
}
public static synchronized Connection getConnection() throws SQLException {
try {
if (connection == null) {
Context initContext = new InitialContext();
Context envContext = (Context) initContext
.lookup("java:/comp/env");
dataSource = (DataSource) envContext.lookup("jdbc/Naresh");
connection = dataSource.getConnection();
} else {
return connection;
}
} catch (NamingException e) {
e.printStackTrace();
}
return connection;
}
}
Otherwise everyone can create an instance of your class, so it's not a singleton any more. For a singleton by definition there can exist only one instance.
If there no such a private constructor, Java will provide a default public one for you. Then you are able to call this constructor multiple times to create several instances. Then it is not a singleton class any more.
If you don't need lazy initiation:
public class Singleton {
private static final Singleton instance = new Singleton();
// Private constructor prevents instantiation from other classes
private Singleton() { }
public static Singleton getInstance() {
return instance;
}
}
is the best way, because is thread safe.
The Singleton pattern typically includes a non-public constructor, for two reasons. A constructor has to exist because if there's no constructor at all, a public default constructor is included. If you have a public constructor, though, people can just make their own singletons at will (which someone inevitably will, meaning there can be more than one).
It doesn't have to be private, though. In fact, as i heard it, the Singleton pattern as specified by the GoF mentions a protected constructor, for some odd reason. Something about inheritance, i hear, but singletons and inheritance do not play well together at all anyway.
It's even possible to have a public constructor, as long as it can detect whether an instance already exists and throw an exception or something if it does. That'd be enough to guarantee singleness. But it's rather uncommon, because doing it that way complicates things by providing two apparent ways to acquire an instance -- only one of which will actually work. If you don't want outside code to be able to create a second instance, why should a constructor be part of the public interface?
For the singleton pattern you use an private constructor to ensure that no other instances can be created, otherwise it wouldn't be a singleton.
A static class is different from a singleton in that a a singleton class enforces that there is always at most one instance. A static class has no instances, and is just a bundle of static functions and static data.
So for a Singleton class, i.e. one with at most one instance, then a private constructor is required.
In your example, it looks like the Singleton class fits more than the static class- because of the connection and dataSource members. Make those members private, your constructor private and provide static methods that reference a static ConnPoolFactory instance. If instance is null, create a new one, otherwise just use it.
For singletons and utilty classes you can use an enum which is a final class and implicitly defines a private constructor.
enum Singleton {
INSTANCE
}
or
enum Utility {;
}
In your example above you have a utility class because you have no instance fields, methods and don't create an instance.
The comment as you said that If I am complete owner of my application and I will never commit mistake of creating instance of singleton class directly using the public constructor but will use the static method for getting it. But in real world, often application switch hands between multiple developers. If the new developer is not aware that you want only one instance of the class in the application, he/she may accidently create another one by using the public constructor.
It is mandatory. Your code may be fine, but others can use this code and instantiate another object, or you might do it by accident. This way is safe.
Singleton def:
Ensure the only one object need to create for the entire main stack (per main class).
If you want to satisfy above statement then we should give constructor as a private. Actually through singleton we are getting ref not object that's why it is not mandatory then we can create object in other classes but we can't access reference (Constructor as public).
Ex:
public class SingleTon {
private static SingleTon s;
public SingleTon() {}
public static SingleTon getInstance() {
if (s == null) {
s = new SingleTon();
System.out.println("ho ho");
} else{
return s;
}
return s;
}
}
Other class:
public class Demo {
public static void main(String[] args) {
//SingleTon s=SingleTon.getInstance();
SingleTon s11=new SingleTon();
SingleTon s12=new SingleTon();
s11.getInstance();
s12.getInstance();
}
}
Output:
ho ho