Effective java says
"Consider providing static factory methods instead of constructors"
If you have a
class A {
public static A getInstance() {
return new A();
}
}
Does it make sense to provide this method for class A , rather than call new A() in the code.
See here for a nice exposition of the main reasons you might want to do this. In summary:
Named "constructors".
Can return null, if appropriate.
Can return an instance of a derived class, if appropriate.
Reduce verbosity when instantiating variables of generic types.
Another reason comes to mind that the article doesn't mention: Can implement interesting logic to avoid creating new objects all the time (caching based on parameters, recycling, etc.).
For your example above it doesn't make much sense to provide a static constructor. And normally when you provide a static constructor you should make the normal constructor private. Otherwise it is still possible to create an instance with the normal constructor.
I try to explain here with another example, when you could use static factory methods. One of the advantages is, that you can give the factory methods understandable names.
class Complex {
public static Complex fromCartesian(double real, double imag) {
return new Complex(real, imag);
}
public static Complex fromPolar(double modulus, double angle) {
return new Complex(modulus * cos(angle), modulus * sin(angle));
}
private Complex(double a, double b) {
//...
}
}
Complex c = Complex.fromPolar(1, pi)
Or another example would be the Singleton Pattern. There you wan't to provide only one instance. So this is the reason why you make the constructor private and create an own getInstance method where you make sure, that there is always just one instance available.
public class Singleton {
private volatile static Singleton singleton;
private Singleton() {
}
// synchronized keyword has been removed from here
public static Singleton getSingleton() {
if(singleton==null) {
synchronized(Singleton.class){
if(singleton == null) {
singleton = new Singleton();
}
}
}
return singleton;
}
}
Factory Method Pattern Wikipedia
The Singleton pattern with static method calls are a better design if ur looking for a single instance.. because of the reentrant locking nature of static.. providing thread safety and also avoiding out-of-order writes..
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();
}
}
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
I understand that double locking in Java is broken, so what are the best ways to make Singletons Thread Safe in Java? The first thing that springs to my mind is:
class Singleton{
private static Singleton instance;
private Singleton(){}
public static synchronized Singleton getInstance(){
if(instance == null) instance = new Singleton();
return instance;
}
}
Does this work? if so, is it the best way (I guess that depends on circumstances, so stating when a particular technique is best, would be useful)
Josh Bloch recommends using a single-element enum type to implement singletons (see Effective Java 2nd Edition, Item 3: Enforce the singleton property with a private constructor or an enum type).
Some people think this is a hack, since it doesn't clearly convey intent, but it does work.
The following example is taken straight from the book.
public enum Elvis {
INSTANCE;
public void leaveTheBuilding() { ... }
}
Here is his closing arguments:
This approach [...] is more concise, provides the serialization machinery for free, and provides an ironclad guarantee against multiple instantiations, even in the face of sophisticated serialization or reflection attacks. While this approach has yet to be widely adopted, a single-element enum type is the best way to implement a singleton.
On enum constant singleton guarantee
JLS 8.9. Enums
An enum type has no instances other than those defined by its enum constants. It is a compile-time error to attempt to explicitly instantiate an enum type (§15.9.1).
The final clone method in Enum ensures that enum constants can never be cloned, and the special treatment by the serialization mechanism ensures that duplicate instances are never created as a result of deserialization. Reflective instantiation of enum types is prohibited. Together, these four things ensure that no instances of an enum type exist beyond those defined by the enum constants.
On lazy initialization
The following snippet:
public class LazyElvis {
enum Elvis {
THE_ONE;
Elvis() {
System.out.println("I'M STILL ALIVE!!!");
}
}
public static void main(String[] args) {
System.out.println("La-dee-daaa...");
System.out.println(Elvis.THE_ONE);
}
}
Produces the following output:
La-dee-daaa...
I'M STILL ALIVE!!!
THE_ONE
As you can see, THE_ONE constant is not instantiated through the constructor until the first time it's accessed.
I see no problem with your implementation (other than the fact that the lock for the singleton-monitor may be used by other methods, for other reasons, and thus, unnecessarily, prevent some other thread from getting the instance). This could be avoided by introducing an extra Object lock to lock on.
This Wikipedia article suggests another method:
public class Something {
private Something() {
}
private static class LazyHolder {
private static final Something INSTANCE = new Something();
}
public static Something getInstance() {
return LazyHolder.INSTANCE;
}
}
From the article:
This implementation is a well-performing and concurrent implementation valid in all versions of Java.
...
The implementation relies on the well-specified initialization phase of execution within the Java Virtual Machine (JVM); see section 12.4 of Java Language Specification (JLS) for details.
My preference is to just do:
class Singleton {
private static final INSTANCE = new Singleton();
private Singleton(){}
public Singleton instance(){
return INSTANCE;
}
}
It is rare that you need lazy initialization. You should always start with eager initialization and only change to lazy initialization if you see problems. Unless you have measured and pinpointed Singleton instantiation as the culprit of performance problem, just use eager initialization. It's simpler and more performant.
You could use enum for sure, but personally I don't bother because the benefit over normal eager instantiation is security (against reflection attack), and most of the time my code is vulnerable to such attacks anyways :p
Josh Bloch recommends 2 solutions:
1) worser:
class Singleton {
public static Singleton instance = new Singleton();
...
}
2) better:
public enum Singleton {
INSTANCE;
...
}
You can use this snippet of code from wiki
public class Singleton {
// Private constructor prevents instantiation from other classes
private Singleton() {}
/**
* SingletonHolder is loaded on the first execution of Singleton.getInstance()
* or the first access to SingletonHolder.INSTANCE, not before.
*/
private static class SingletonHolder {
private static final Singleton INSTANCE = new Singleton();
}
public static Singleton getInstance() {
return SingletonHolder.INSTANCE;
}
}