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;
}
}
Related
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;
}
}
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
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
The standard method of implementing singleton design pattern is this:
public class Singleton {
private static Singleton instance = new Singleton();
public static Singleton getInstance() {
return instance;
}
private Singleton() {}
}
I was wondering if you could also implement it like this:
public class Singleton {
private Singleton() {}
public final static Singleton INSTANCE = new Singleton();
}
and if yes which version is better?
Neither. In both cases, a trusted consumer can invoke the private constructor via reflection. An additional problem is that it these implementation don't play nicely with serialization unless you take extra steps to make it so (by default, if you take the naïve approach, every time a Singleton is deserialized, it will create a new instance).
The correct solution is to use an enum that defines a single value.
public enum Singleton {
INSTANCE;
// methods
}
From Effective Java:
While this approach is yet to be widely adopted, a single-element enum type is the best way to implement a singleton.
Why you not use enum for realisation Singleton?
public enum SingletonEnum {
Instance;
private static String testStr = "";
public static void setTestStr(String newTestStr) {
testStr = newTestStr;
}
public static String getTestStr() {
return testStr;
}
public static String sayHello(String name) {
return "Hello " + name;
}
}
In my opinion first one is better as it looks more aligned to Object oriented approach.
While there's nothing particularly wrong with either solution, this solution from Wikipedia should give you the best compatibility and give you a thread-safe singleton:
University of Maryland Computer Science researcher Bill Pugh has written about the code issues underlying the Singleton pattern when implemented in Java.[11] Pugh's efforts on the "Double-checked locking" idiom led to changes in the Java memory model in Java 5 and to what is generally regarded as the standard method to implement Singletons in Java. The technique known as the initialization on demand holder idiom, is as lazy as possible, and works in all known versions of Java. It takes advantage of language guarantees about class initialization, and will therefore work correctly in all Java-compliant compilers and virtual machines.
The nested class is referenced no earlier (and therefore loaded no earlier by the class loader) than the moment that getInstance() is called. Thus, this solution is thread-safe without requiring special language constructs (i.e. volatile or synchronized).
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 {
public static final Singleton INSTANCE = new Singleton();
}
public static Singleton getInstance() {
return SingletonHolder.INSTANCE;
}
}
Basically I have a class which an instance of is created via a Singleton class. The class should never been instantiated via any other means than the singleton class. My question is can the class be effectively 'not seen' by other classes, apart from Singleton.
I know inner classes and different pacakages etc would help, but I'm curious to see if anyone has a nice solution to this.
Thanks for replies
Just refactor class itself as singleton. Private constructor and etc.
An easy and efficient way to do Singleton with an Enum:
public enum Singleton {
INSTANCE;
public void execute (String arg) {
//... perform operation here ...
}
}
In a sample scenario, using your API, do I need to declare?:
ToBeInvisibleClass instance = TheSingleton.getThatInvisibleInstnace();
If the answer is Yes, then the answer to your question is No since I need to declare a variable and for that I need the type to visible. If the answer is No, then using inner/nested class seems to be a proper approach or making the class itself the singleton.
Java has no "friend" concept like C++
You mentioned nested classes (real inner classes will not work because they need the outer) and packages.
Other approaches to protected other classes but one from creating an instance are not known to me.
But in general there is no reason to build a singleton by an helper class.
You could build singleton using enums or static final vars
What is the best approach for using an Enum as a singleton in Java?
public enum Elvis implements HasAge {
INSTANCE;
private int age;
#Override
public int getAge() {
return age;
}
}
class X {
public static final X instance = new X ();
private X () {
}
...
}
To assure that instantiation only occurs through your class method, you can do the following:
Make the default constructor private
Save your singleton instance in a private method
Use a public static method to provide the instance to the clients:
In this site there's a nice example:
public class MySingleton {
private static MySingleton _instance = new MySingleton();
private MySingleton() {
// construct object . . .
}
public static MySingleton getInstance() {
return _instance;
}