Implementing Singleton pattern - java

If we are implementing a class as a singleton, we do the following
class Single
{
private Single singleton;
public static Single getInstance()
{
if(null == singleton)
{
singleton = new Single();
}
return singleton;
}
//then we make the constructor private
private Single()
{
}
}
Considering the above, wiil it be a good idea to override clone() as well to prevent multiple instances of the class?

There is no clone() method in the Cloneable interface. As #Ivan points out, if your class does not implement Cloneable then calling Single#clone() will throw a CloneNotSupportedException.
That said, cloning is something that happens infrequently in well-written Java these days. As Josh Bloch writes in Effective Java, Item 11:
The Cloneable interface was intended as a mixin interface (Item 18) for objects to
advertise that they permit cloning. Unfortunately, it fails to serve this purpose. Its
primary flaw is that it lacks a clone method, and Object's clone method is protected.
You cannot, without resorting to reflection (Item 53), invoke the clone
method on an object merely because it implements Cloneable. Even a reflective
invocation may fail, as there is no guarantee that the object has an accessible
clone method. Despite this flaw and others, the facility is in wide use so it pays to
understand it.
...basically, people don't/shouldn't use clone(). It's a poorly designed interface, and if you want your objects to be cloneable, it's better to provide a copy constructor or copy factory method (code stolen from Item 11):
public Yum(Yum yum); // copy constructor
public static Yum newInstance(Yum yum); // copy factory
And while I'm talking about Effective Java, there's a better way to write a singleton, assuming that you really do need one (which is a big if!).
As of release 1.5, there is a third approach to implementing singletons. Simply
make an enum type with one element:
// Enum singleton - the preferred approach
public enum Elvis {
INSTANCE;
public void leaveTheBuilding() { ... }
}
This approach is functionally equivalent to the public field approach, except that it
is more concise, provides the serialization machinery for free, and provides an
ironclad guarantee against multiple instantiation, 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.

if you dont implement clonable it should not be clonable.
p.s.
a cleaner java single is:
class Single {
private static final Single singleton = new Single();
private Single() { }
public static Single getInstance() {
return single;
}
}

Any calls to clone() on your singleton object will fail, as explained here:
http://download.oracle.com/javase/1.4.2/docs/api/java/lang/Object.html#clone%28%29
If the class is not Cloneable (does not specify implements Cloneable), a CloneNotSupportedException error will be thrown.
So no, it's not necessary. And less code is goooood :)

By default, the clone() method is marked as protected, but if your class extends another class that does support cloning, it is possible to violate the design principles of the singleton.
In that case, yes this is a good idea:
public Object clone()
throws CloneNotSupportedException
{
throw new CloneNotSupportedException();
}

As he said, there is nothing to override.
Regarding your singleton implementation in general - there are many, many flaws with it (apart from the obvious mistakes in the code sample). Think about multithreading, reflection, serialization/deserialization. Making it as an enum with 1 constant will be much easier on your side since you won't have to write any code to enforce the property.
Take a look at this answer to another question (disregard the part about hashCode()). Also take note of the comments.

Related

What limits clone() from being accessible for all objects? [duplicate]

What is the specific reason that clone() is defined as protected in java.lang.Object?
The fact that clone is protected is extremely dubious - as is the fact that the clone method is not declared in the Cloneable interface.
It makes the method pretty useless for taking copies of data because you cannot say:
if(a instanceof Cloneable) {
copy = ((Cloneable) a).clone();
}
I think that the design of Cloneable is now largely regarded as a mistake (citation below). I would normally want to be able to make implementations of an interface Cloneable but not necessarily make the interface Cloneable (similar to the use of Serializable). This cannot be done without reflection:
ISomething i = ...
if (i instanceof Cloneable) {
//DAMN! I Need to know about ISomethingImpl! Unless...
copy = (ISomething) i.getClass().getMethod("clone").invoke(i);
}
Citation From Josh Bloch's Effective Java:
"The Cloneable interface was intended as a mixin interface for objects to advertise that they permit cloning. Unfortunately it fails to serve this purpose ... This is a highly atypical use of interfaces and not one to be emulated ... In order for implementing the interface to have any effect on a class, it and all of its superclasses must obey a fairly complex, unenforceable and largely undocumented protocol"
The Clonable interface is just a marker saying the class can support clone. The method is protected because you shouldn't call it on object, you can (and should) override it as public.
From Sun:
In class Object, the clone() method is declared protected. If all you do is implement Cloneable, only subclasses and members of the same package will be able to invoke clone() on the object. To enable any class in any package to access the clone() method, you'll have to override it and declare it public, as is done below. (When you override a method, you can make it less private, but not more private. Here, the protected clone() method in Object is being overridden as a public method.)
clone is protected because it is something that ought to be overridden so that it is specific to the current class. While it would be possible to create a public clone method that would clone any object at all this would not be as good as a method written specifically for the class that needs it.
The Clone method can't be directly used on any object, which is why it is intended to be overriden by the subclass.
Of course it could be public and just throw an appropriate exception when cloning is not possible, but i think that would be misleading.
The way clone is implemented right now makes you think about why you want to use clone, and how you want your object to be cloned.
IMHO it's as simple as this:
#clone must not be called on non-cloneable objects, therefore it is not made public
#clone has to be called by subclasses ob Object that implement Cloneable to get the shallow copy of the right class
What's the right scope for methods that shall be callable by subclasses, but not by other classes?
It's protected.
Classes implementing Cloneable of course will make this method public so it can be called from other classes.
It is protected because the default implementation does a shallow memberwise copy of all fields (including private), circumventing constructor. This is not something an object might be designed to handle in the first place (for example, it might keep track of created object instances in a shared list, or something similar).
For the same reason, the default implementation of clone() will throw if the object it's called on doesn't implement Cloneable. It's a potentially unsafe operation with far-reaching consequences, and therefore author of the class must explicitly opt-in.
From the javadoc of cloneable.
* By convention, classes that implement this interface (cloneable) should override
* <tt>Object.clone</tt> (which is protected) with a public method.
* See {#link java.lang.Object#clone()} for details on overriding this
* method.
* Note that this interface does <i>not</i> contain the <tt>clone</tt> method.
* Therefore, it is not possible to clone an object merely by virtue of the
* fact that it implements this interface. Even if the clone method is invoked
* reflectively, there is no guarantee that it will succeed.
So you could call clone on every object but this would give you most of the time not the results you want or an exception. But is only encouraged if you implement cloneable.
Clone() method has a check internally 'instance of Cloneable or not'.This is how Java team might thought will restrict the improper use of clone() method.clone() method is protected i.e. accessed by subclasses only. Since object is the parent class of all sub classes, so Clone() method can be used by all classes infact if we don't have above check of 'instance of Cloneable'. This is the reason Java team might have thought to restrict the improper use of clone() by having the check in the clone() method 'is it instance of Cloneable'.
Hence whatever classes implement cloneable can use clone() method of Object class.
Also since it made protected, it is available to only those sub classes that implements cloneable interface. If we want to make it public, this method has to be overridden by the sub class with their own implementation of it.
Yes, same problem that I met.
But I solve it by implementing this code
public class Side implements Cloneable {
public Side clone() {
Side side = null;
try {
side = (Side) super.clone();
} catch (CloneNotSupportedException e) {
System.err.println(e);
}
return side;
}
}
Just as the before someone said.
Well, also the sun developers are only human, and they did indeed make huge mistake to implement the clone method as protected, the same mistake as they implemented a non-functioning clone method in ArrayList! So, in general, there exist a much deeper misunderstanding of even experienced Java programmers about the clone method.
However, I've recently found a fast and easy solution to copy any object with all its content, no matter how it is built and what it contains, see my answer here: Bug in using Object.clone()
Again, Java JDK framework shows brilliant thinking:
Cloneable interface does not contain a "public T clone();" method because it acts more like an attribute (eg. Serializable) which allows an instance it to be cloned.
There is nothing wrong with this design because:
Object.clone() will not do what you want with your custom-defined class.
If you have Myclass implements Cloneable => you overwrite clone() with
"public MyClass clone()"
If you have MyInterface extends Cloneable and some MyClasses implementing MyInterface:
simply define "public MyInterface clone();" in the interface and every method using MyInterface objects will be able to clone them, no matter their MyClass-class.

Can we avoid inheritance without using final keyword?

I just want to know that can i have 2 classes A and B.
I don't want to allow class B to extends class A.
What technique should i apply in class A so class B cannot inherit class A.
Don't want to make class A final. Any other solution instead of making class A final?
In fact, the practice that I try to follow, and that Josh Bloch recommends, in his Effective Java book, is exactly the inverse rule of the one you've been told: Unless you have thought about inheritance, designed your class to be inherited, and documented how your class must be inherited, you should always disable inheritance.
I would recommend reading this chapter of Effective Java (you won't regret buying it), and showing it to the person who told you about this rule.
The most obvious reason to disallow inheritance is immutability. An immutable object is simple to use (only one state), can be cached, shared between many objects, and is inherently thread-safe. If the class is inheritable, anyone can extend the class and make it mutable by adding mutable attributes.
https://stackoverflow.com/a/10464466/5010396
This is not possible in "nice ways". The java language allows you to either have the final keyword on your class definition, or to not have it.
As pointed out by others: you can make all constructors private, then subclassing becomes practically impossible, as the subclass constructors have no super class constructor to call.
In case you need to instantiate A, you could still have a factory method, like:
public class A {
private A() { ... }
private A(String foo) { ... }
public static A newInstance(String foo) { return new A(foo); }
for example.
But keep in mind: code is written for your human readers. If your intent is to have a final class, then the correct answer is to use that keyword final.
Plus: making your class final allows the JIT to do a few more things, as it doesn't have to worry about polymorphism at any point (so it can directly inline method code, without any additional checks). So using final can result in slightly improved performance. On the other hand, it limits your ability to unit test things (for example: standard Mockito can't mock final classes).
You can mark the constructor of A class as private. :)
PS: If you also want to avoid reflection attacks then throw some Error from constructor
and also mark it private.
You have an option to restrict in constructor like this.
if (this.getClass() != MyClass.class) {
throw new RuntimeException("Subclasses not allowed");
}
For further details check the post.
https://stackoverflow.com/a/451229/6742601
I don't understand the specific use case of your requirement but this could work.
If you are open to make changes in B
In B's every constructor check for is it is an instance of A then throw an error.
if(A.class.isAssignableFrom(B.class)) {
System.out.println(true);
throw new IllegalStateException();
}
else
System.out.println(false);
You can do one of the following to avoid inheritance without using final keyword:
Use private constructor(s).
Mark every method final so children can't override them.
Throw Runtime exception in the constructor if want to limit inheritance for some unwanted children (although v.rude) e.g
if (this.getClass() != FavoriteChild.class) throw new RuntimeException("Not Allowed")

Why no default clone() in Cloneable in Java 8

Cloneable in Java is inherently broken. Specifically, my biggest problem with the interface is it expects a method behavior that doesn't define the method itself. So if traversing through a Cloneable list you must use reflection to access its defined behavior. However, in Java 8, we now have default methods and now I ask why there isn't a default clone() method in Cloneable.
I understand why interfaces cannot default Object methods, however, this was an explicit design decision and so exceptions can be made.
I sort of envision deprecating Object.clone() and changing its interior code to something like:
if(this instanceof Cloneable) {
return ((Cloneable) this).clone();
}
else {
throw new CloneNotSupportedException();
}
And moving on whatever magic makes clone() do its thing as a default method in Cloneable. This doesn't really fix that clone() can still easily be implemented incorrectly, but that's another discussion in of itself.
As far as I can still this change would be completely backwards compatible:
Classes that currently override clone() but didn't implement Cloneable (WHY?!) would still be technically okay (even if functionally impossible, but this is no different then it was before).
Classes that currently override clone(), but did implement Cloneable would still function the same on its implementation.
Classes that don't currently override clone(), but did implement Cloneable (WHY?!) would now follow a specification, even if it's not completely functionally correct.
Those that used reflection and referred to Object.clone() would still functionally work.
super.clone() would still be functionally the same even if it's referencing Object.clone().
Not to mention this would solve a huge problem that Cloneable is. While tedious and still easy to implement incorrectly, it would solve a huge object oriented problem with the interface.
The only problem I can see with this is those that implement Cloneable aren't obligated to override clone(), but this is no different than it was before.
Has this been discussed internally, but never came to fruition? If so, why? If it's for the reason that interfaces cannot default Object methods, wouldn't it make sense to make an exception in this case since all objects inheriting Cloneable are expecting clone() anyway?
Your question is somewhat broad and more of a discussion, but I can shed some light on this matter.
In Effective Java™, Joshua Bloch gives quite the rundown on the situation. He opens with a bit of history behind Cloneable
The Cloneable interface was intended as a mixin interface for objects to
advertise that they permit cloning. Unfortunately, it fails to serve this purpose. Its primary flaw is that it lacks a clone method, and Object’s clone method is protected. You cannot, without resorting to reflection, invoke the clone method on an object merely because it implements Cloneable.
and continues with the reasoning
[Cloneable] determines the behavior of Object’s protected clone implementation: if a class implements Cloneable, Object’s clone method returns a field-by-field copy of the object... This is a highly atypical use of interfaces and not one to be emulated. Normally, implementing an interface says something about what a class can do for its clients. In the case of Cloneable, it modifies the behavior of a protected method on a superclass.
and
If implementing the Cloneable interface is to have any effect on a class, the
class and all of its superclasses must obey a fairly complex, unenforceable, and
thinly documented protocol. The resulting mechanism is extralinguistic: it creates an object without calling a constructor.
There are a lot of details that go into this, but to note just one problem:
The clone architecture is incompatible with normal use of final fields referring to mutable objects.
I think this is enough to reason against having a default method in the interface do the cloning. It would be extremely complicated to implement it correctly.
My experience is probably far from being mainstream, but I use clone() and support the current design of Cloneable. Probably it would be better to have it as annotation instead, but Cloneable appeared long before the annotations. My opinion is that Cloneable is a low-level thing and nobody should do something like obj instanceof Cloneable. If you are using Cloneable in some business-logic, it's much better to declare your own interface or abstract class which exposes clone() to public and implement it in all of your business-logic objects. Sometimes you will probably want not to expose clone() actually, but create your own method which uses clone() internally.
For example, consider that you have an hierarchy of named objects where name cannot be changed after construction, but you want to allow cloning them with new name. You can create some abstract class like this:
public abstract class NamedObject implements Cloneable {
private String name;
protected NamedObject(String name) {
this.name = name;
}
public final String getName() {
return name;
}
public NamedObject clone(String newName) {
try {
NamedObject clone = (NamedObject)super.clone();
clone.name = newName;
return clone;
}
catch(CloneNotSupportedException ex) {
throw new AssertionError();
}
}
}
Here even though you implement Cloneable, you want to use clone(), but don't want to expose it publicly. Instead you provide another method which allows to clone with another name. So having public clone() in Cloneable would unnecessarily pollute the public interface of your classes.
Another case where I use Cloneable is the implementation of Spliterator.trySplit(). See the implementation of simple spliterator which returns given number of constant objects. It has four specializations (for Objects, ints, longs and doubles), but thanks to clone() I can implement trySplit() only once in the superclass. Again, I don't want to expose clone(), I just want to use it by myself.
So to conclude, not having clone() method in Cloneable interface is actually more flexible as it allows me to decide whether I want to have it public or not.

Singleton – the proper way

public enum YourSingleton {
INSTANCE;
public void doStuff(String stuff) {
System.out.println("Doing " + stuff);
}
}
YourSingleton.INSTANCE.doStuff("some stuff");
Here is the original link,
http://electrotek.wordpress.com/2008/08/06/singleton-in-java-the-proper-way/
I am asking why we can call the function doStuff this way in Java.
In Java, enum can do everything that class can [1]. YourSingleton.INSTANCE creates an instance of YourSingleton, so you can then invoke methods as if it were a regular class instance, which it basically is.
See the official Java docs for a more in-depth discussion on Enum Types: http://download.oracle.com/javase/tutorial/java/javaOO/enum.html
[1] enum does not have a practical implementation of inheritance. Since all enum types implicity inherit java.lang.Enum and Java does not support multiple inheritance, you cannot extend anything else.
The Traditional way to implementing singleton is fine, but to maintain its Status as true singleton, it needs to protect itself from sophisticated Serialization and Reflection Attacks. The general way of doing this, is by making the class Implement Serializable, make all instance fields Transient and also implement a readResolve method. (that return the same singleton instance).
The Enum Singleton pattern provides all these features out of the box. But the main reason, I like the Enum variant is its readability. According to me, it conveys what it does, in a much more concise fashion, than a traditional singleton.( You do not have to explain to a new developer, all the vagaries involved in serialization and how serialization might break the singleton guarantee and why you need readResolve method etc etc..)
I know this is not really what you asked for but this is what I do when I need a class to be a singleton, which may help. I create one static getInstance method that either creates and returns a new instance of the class if none exist or I return the existing reference of itself, and I make the constructor for this class private.
For example:
public class NameOfClass{
private static NameOfClass variableReferencingThisClass=new NameOfThisClass();
private NameOfClass(){}
public static NameOfClass getInstance(){
return variableReferencingThisClass;
}
}
You can also use the double-lock singleton creation. Assuming the class is MyObject, has a private constructor, and has a declared a static field instance as null. However, this is not a guarantee that 2 singletons will not end up getting created, but is a much closer attempt to thread safety than a single check.
public static MyObject getInstance()
{
if (instance == null)
{
synchronized(MyObject.class) {
if (instance == null)
instance = new MyObject();
}
}
return instance;
}

simulation of static class in java

What do you think of the following way to simulate a static class in java?
You can add non static methods but you wouldn't be able to call them.
/**
* Utility class: this class contains only static methods and behaves as a static class.
*/
// ... prevent instantiation with abstract keyword
public abstract class Utilities
{
// ... prevent inheritance with private constructor
private Utilities() {}
// ... all your static methods here
public static Person convert(String foo) {...}
}
That is the usual way. However, there is not need for the abstract keyword. Using a private constructor is sufficient because
it prevents the creation of objects (from outside the class)
it prevents inheritance
The abstract keyword suggests the user that users of the class might implemented the class what is not the case here.
Item 4 in Effective Java (a very... effective book) says:
// Noninstantiable utility class
public final class Utility {
private Utility() {
throw new AssertionError();
}
}
because the explicit costructor is private:
you cannot instantiate it
you cannot extend it (as if it was declared as final)
The AssertionError isn't required but it provides another small benefit: it prevents that the costructior is accidentally invoked from within the class.
You can also create a specific annotation, like #BagOfFunction, and annotate your class:
#BagOfFunctions
public final class Utility {
private Utility() {
throw new AssertionError();
}
}
basically you trade a comment for a self-documenting annotation.
My FindBugs plugin suggests rather final class instead of abstract class. And I use that in my project. It seems to be a widespread idiom if it became a rule that is checked by FindBugs.
i would say, if you habe already a private constructor
private Utilities() {}
the abstract keyword is not neccessary. rather make it final.
the difference to your version is marginal, for any practical means.
I prefer making such classes final, but not abstract. Though it is just a matter of personal style.
By the way, I suppose it is still possible to call its instance methods if you put some energies. E.g. one can try using objenesis to create instance of class.
I'll have to agree with those above. Use "final" instead of "abstract". Remember, words like "final" and "abstract" are as much a means of communicating with your fellow programmers as they are instructions to the machine. Abstract implies that there will be descendant classes later, whereas final decidedly means that you will not, save through refactoring, see anything descended of this class (which is your intended meaning).
Further, in most standards I've seen, and consistently in my company, it is considered best practice to make the abstract class something which is specifically left unused, save as a parent of other classes. "Abstract" is treated as "blueprint" or "general structure", you would never drive an "abstract" car. On the other hand, final classes are instantiated perpetually, especially with Factory patterns.
My suggestion is: prevent incorrect use (i.e. instantiation) by placing javadocs
Isn't that simpler? I think your teammates are able to read ;)

Categories

Resources