Singleton contract using inheritance? - java

I'm trying to create a framework where Singleton objects can get the core of their implementation from. The use for this is so if I make multiple Singleton classes, I don't need to re-write their (while simple) implementations over and over.
I tried this:
public abstract class Singleton
{
protected static final Lock mutex = new ReentrantLock(true);
// Not even subclasses are allowed to mess with `instance`.
private static Singleton instance = null;
// Here is the problem, static methods cannot be abstract.
protected static abstract Singleton init();
public static Singleton get()
{
mutex.lock();
// The super class has no idea how to instantiate
// this singleton, so let subclasses handle that
// via the abstract init method
if (instance == null)
instance = init();
mutex.unlock();
return instance;
}
}
But it really cannot work because the whole concept of static members with inheritance doesn't go well together.
My other option is to do:
public enum Singleton
{
INSTANCE
}
But since enum cannot be extended, I cannot do:
public enum MySingleton extends Singleton
{
// Member variables and functions here
...
}
I could have every implementation just be an enum and the only code I have to repeat (I think?) is INSTANCE unless I'm missing something? The only downside I see there is the Singleton is created at the beginning of the runtime and not on-demand later on in the program.
I could also do an interface but then I get stuck here:
public interface Singleton
{
Singleton instance = null;
default void set(Singleton s)
{
assert instance == null;
assert s != null;
// cannot do this, as `instance` is FINAL
instance = s;
}
}
What's the best way to do define a Singleton contract without having to retype the entire implementation over again?
Thanks

Related

Use factory to build singleton object

I'm trying to create some singleton object with a factory:
public class MyObjectFactory {
private MyObject myObject;
public MyObject getInstance(boolean newInstance) {
if (newInstance) {
// return new object
} else {
// return the old object
}
}
}
I want to use the getInstance(boolean newInstance) method to generate a new object or reuse the existing singleton object.
if newInstance is true: I will generate a new singleton object
if newInstance is false: if myObject is null, then generate a new one and return, or if myObject is not null, just return it.
And this getInstance(boolean newInstance) must be thread safe. Any idea how?
According to your comment, this is one way to implement what you want:
public class MyObjectFactory {
private volatile MyObject inst;
public synchronized MyObject getInstance(boolean newInstance) {
if(newInstance) {
inst = new MyObject(...);
}
return inst;
}
}
Making the field volatile means that the value is not cached in the CPU, so changes are immediately visible to all threads. Making the method synchronized ensures that only one thread can enter it at the same time.
This is not how Singletons work. The whole point of a Singleton is to have a single instance across the program of a certain class. Parameterizing your factory method to either get a new instance or a previous one does not fall into the definition of a Singleton.
Also, the best Singleton implementation is known as the Bill Pugh Singleton:
public class BillPughSingleton {
private BillPughSingleton() {}
public static BillPughSingleton getInstance() {
return SingletonHelper.INSTANCE;
}
private static class SingletonHelper {
private static final BillPughSingleton INSTANCE = new BillPughSingleton();
}
}
The William Pugh implementation ensures multi-thread safety and the best performances as the nested static class is loaded by the class loader only when the method getInstance() is invoked. In fact, a static nested class is simply a static member of the outer class (no difference from a static field or a static method in terms of creation time). The static member is created only when the class is used, so since no instances of the BillPughSingleton can be created with a constructor, a single thread-safe instance is generated only when the outer class is used via the getInstance() method.
EDIT
If what you're asking is something that either creates a new instance if this is null or returns/overrides the existing one. Then, what you need is not a singleton but a retriever class. Besides, you should also take into consideration in your design whether this retriever class will be used in multi-thread scenarios or not. Here is a basic implementation:
class MyRetriever {
private static MyClass instance;
//Private constructor to force the factory method invocation
private MyRetriever() {}
//Synchronizing the method in order to avoid race condition and establish a happens-before relationship between threads
public synchronized static MyClass getInstance(boolean flagOverride) {
if (flagOverride || instance == null){
instance = new MyClass();
}
return instance;
}
}

Is creating a "master-class" considered using a singleton or something else?

I want to know if code, containing a "master-class"(A class that should have only one instance) is considered implementing the "Singleton" design pattern or if there is another design pattern that follows this concept.
I created a class "GUI" and a class "MasterControl"
The class "MasterControl" defines alot of methods that interact with the GUI and contains a single "GUI" Instance on which it operates.
Code to demonstrate the basic idea.
public static void main(String[] args){
MasterControl controller = new MasterControl();
}
public class MasterControl{
private GUI Servant;
public MasterControl(){
Servant = new GUI(this);
}
}
public MasterControl(){
Servant = new GUI(this);
}
public class GUI{
GUIComponent c;
MasterControl master;
public GUI(MasterControl master){
this.master = master;
c = new GUIComponent(master);
}
}
//And so on
A Singleton design pattern means that it is impossible to create more than one instance of that class. Code that contains a "master class" is usually a class that represents the starting point of the code, it is proper format to initialize it once, but there is technically nothing stopping us from creating another instance of it. The presence of a master class does not necessarily make it a Singleton design pattern.
The classic implementation of a Singleton design pattern involves a private constructor with its own 'getter' method, as well as a static & uninitialized instance variable which will represent the single instance of the Singleton class. This design makes the constructor only available through the getter method, and can therefore be programmed to only be called when the getter method is called the first time. This would initialize the instance variable, which would then be returned from here on out. It would look something like this:
class Singleton {
private static Singleton instance;
private Singleton() {}
public static Singleton getInstance() {
if(instance == null) {
instance = new Singleton();
return instance;
}
}

Singleton + Abstract class issue

I'm trying to define this inheritance:
public abstract class GameAction extends Observable {
protected static GameAction instance = null;
protected GameAction() {
// Exists only to defeat instantiation.
}
//All GameActions are singletons
public static abstract GameAction getInstance();
}
public class ChooseAnswerAction extends GameAction {
protected ChooseAnswerAction() {
// Exists only to defeat instantiation.
}
//All GameActions are singletons
#Override
public static GameAction getInstance() {
if(instance == null) {
instance = new ChooseAnswerAction();
}
return instance;
}
}
The problem is that the getInstance() method in the second class doesn't find the same one on his father, therefor it asks me to remove the #Override.
Also on the parent class I get the following error:
The abstract method getInstance in type GameAction can only set a visibility modifier, one of public or protected
The only way I could fix this error was taking out the static modifier, but I need it...
Thank's for your time!
Here is my go to link on singleton. Since Aleksey Shipilёv has made a very detailed post - I am linking you there.
http://shipilev.net/blog/2014/safe-public-construction/
In your case, since you are returning the child singleton instance, I would recommend that the instance object be in the child class. Also, you may want a better design and think about using a singleton factory.
The short answer is, that you can't override static methods since they are bound to the superclass.
The long answer is, that this makes implementing singleton inheritances complicated (assuming you want to hold the instance in the superclass). See singleton and inheritance in Java

2 implementations of Singleton

I know of 2 ways to implement the singleton pattern in java and im wondering which one is better and why.
the first way is:
declare the constructor of the class private
have everything inside the class static - basiclly have the class instance itself be the singleton
second way is:
declare the constructor of the class private
have a static member to hold the singleton (which may be an instance of the class)
have a static getInstance() method
I tend to think that even though the second approach is the most common, the first approach may produce better code readability, both approaches seem similiarly efficient in runtime complexity, so i dont really get the reasons behind why the second approach is way more common and considered better practice...
enlighten me!
The first approach is not a singleton. A singleton is a class of which precisely one instance, no more, no less, can exist. The first thing is sometimes called a "static class", a "utility class," or an "uninstantiable class."
There are a number of things that you can do with a "real" singleton that you can't do with a utility class. For example, you can have a singleton that implements an interface or extends another class; you can't do that with the all-static-methods thing. The all-static-methods class is generally evidence that no object oriented design analysis was done
As far as how many ways there are to implement the singleton pattern in Java, there are actually quite a number of interesting ways, using different language features to defer initialization until absolutely needed: class loading, enumerations, or just a synchronized block and an if.
Testability of other classes that use the singleton is hampered by static methods. With an instance you can substitute a mock object or other forms of test double.
Advantages to the object-based singleton
Will your "singleton" ever, under any possibly non-imaginable circumstances, become a non-singleton?
Perhaps you'll want per-thread, per-connection, or some other categorization?
Door #2 leaves you with a future, without having to rewrite code.
You may have a singleton, but do you have only one implementation of that singleton? A common pattern is to have a factory method look at the runtime environment and make a determination as to which implementation of the "service" being offered by the singleton is appropriate. The commons-logging LogFactory is example of this type of singleton.
If I get your question, right.
Why is this #2
public class MySingleton {
static private MySingleton instance=new MySingleton();
private MySingleton() {}
static public MySingleton getInstance() { return instance; }
}
better than #1
...Sorry I don't get the first point...
-> Actually reading from other comments I got it. I confirm, having static methods doesn't mean you have a singleton. So the comparison is not even fair ;-/
Whatever it is, the reason why #2 is better is because of multi-threading.When the singleton is initialized from a static initializer, the jvm makes sure only one thread instantiates the class.
Well there are few interesting ways to implement singleton pattern. Let me recollect few of those implementations which i have read about:
The second approach you have mentioned in your question. (Not thread safe)
When you developing multithreaded applications you may have to use a lock (simple thread safety)
public sealed class Singleton
{
static Singleton instance=null;
static readonly object padlock = new object();
Singleton()
{
}
public static Singleton Instance
{
get
{
lock (padlock)
{
if (instance==null)
{
instance = new Singleton();
}
return instance;
}
}
}
}
Double check locking
public sealed class Singleton
{
static Singleton instance=null;
static readonly object padlock = new object();
Singleton()
{
}
public static Singleton Instance
{
get
{
if (instance==null)
{
lock (padlock)
{
if (instance==null)
{
instance = new Singleton();
}
}
}
return instance;
}
}
}
Not lazy, but thread-safe without using locks
public sealed class Singleton
{
static readonly Singleton instance=new Singleton();
// Explicit static constructor to tell C# compiler
// not to mark type as beforefieldinit
static Singleton()
{
}
Singleton()
{
}
public static Singleton Instance
{
get
{
return instance;
}
}
}
Fully Lazy Initialization
public sealed class Singleton
{
Singleton()
{
}
public static Singleton Instance
{
get
{
return Nested.instance;
}
}
class Nested
{
// Explicit static constructor to tell C# compiler
// not to mark type as beforefieldinit
static Nested()
{
}
internal static readonly Singleton instance = new Singleton();
}
}
The third approach wont work in java.Becos Java memory model doesn't ensure that the constructor completes before the reference to the new object is assigned to instance.
Hope this helps you.
Perhaps consider implementing a singleton using an enum:
public enum Singleton {
INSTANCE;
public void doStuff() {
System.out.println("Whoopee");
}
}
and call it like Singleton.INSTANCE.doStuff()
This is recommended in the book Effective Java by Josh Bloch

Should I create protected constructor for my singleton classes?

By design, in Singleton pattern the constructor should be marked private and provide a creational method retuning the private static member of the same type instance. I have created my singleton classes like this only.
public class SingletonPattern {// singleton class
private static SingletonPattern pattern = new SingletonPattern();
private SingletonPattern() {
}
public static SingletonPattern getInstance() {
return pattern;
}
}
Now, I have got to extend a singleton class to add new behaviors. But the private constructor is not letting be define the child class. I was thinking to change the default constructor to protected constructor for the singleton base class.
What can be problems, if I define my constructors to be protected?
Looking for expert views....
If you extend a singleton class via inheritance, you'll have 2 instances of the singleton class running around should someone grab your singleton and the original singleton.
If the original singleton is conceptually really supposed to be a singleton, then using composition is probably the way to go. However, then substitutability is lost (your class is not substitutable for the original singleton; it just uses it).
Do you have a concrete example?
If you do that, it's not a singleton. But perhaps you don't really need a singleton.
This is not the Singleton Class. Imagine I can call getInstance() static method n number of times and I can have n objects of this class thus completely violating Singleton Pattern. To make it Singleton you should check whether object is already created or not in getInstance() method. If already created then you should ignore and do not create again. For example, you can so something similar, please ignore syntax mistakes, just a code to explain, can vary in different languages.
public class SingletonPattern {// singleton class
private static SingletonPattern pattern = new SingletonPattern();
private SingletonPattern() {
}
public static SingletonPattern getInstance() {
if(SingletonPattern == null) {
return new SingletonPattern();
}
}
Old question I know but happened to stumble upon this and think I can add something useful.
It is possible to have a protected constructor in a singleton class. If you want to have polymorphic behavior on your Singleton you can make it an abstract class, set the constructor to protected and delegate creation of the instance to one of the concrete sub classes.
I found the following example in the book "Design Patterns explained":
abstract public class Tax{
static private Tax instance;
protected Tax() {};
abstract double calcTax( double qty, double price);
public static Tax getInstance() {
// code to determine what implementing class to use
instance = USTax.getInstance();
return instance;
}
}
public class USTax extends Tax {
private static USTax instance;
private USTax() {
// instantation local members + Tax abstract class
}
public double calcTax ( double qty, double price){
// implementation
}
public static Tax getInstance() {
if(instance == null)
instance = new USTax();
return instance;
}
}

Categories

Resources