Singleton + Abstract class issue - java

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

Related

Singleton contract using inheritance?

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

Regarding changing the constructor specifier from private to protected of singleton

What would happen if we change the constructor of the singleton from private to protected? How we can prevent it breaking in that case?
Singleton:
public class SingletonObject
{
private static SingletonObject ref;
private SingletonObject () //private constructor
{
System.setSecurityManager(new SecurityManager());
}
public static synchronized SingletonObject getSingletonObject()
{
if (ref == null)
ref = new SingletonObject();
return ref;
}
public Object clone() throws CloneNotSupportedException
{
throw new CloneNotSupportedException ();
}
}
For breaking the singleton the following url contains the required info cracking singleton with other ways.
From Joshua Bloch's Effective Java on Singletons Properties:
The private constructor is called only once, to initialize the public
static final field (...). The lack of public or protected
constructors guarantees a “monoinstance” universe: Exactly one (...)
instance will exist once the Singleton class is initialized—no more, no
less. Nothing that a client does can change this.
So, if you make your Singleton Constructor protected you're exposing your Constructor to let any class in the same package to make instances an instance of SingletonObject. If that happens, your Singleton Pattern is broken.
Relaxing the access modifiers of the constructor on any way -making it protected, public or default- is an open gate to instance generation, and that's not desired in a Singleton implementation.
Simple: Changing the constructor access modifier from private to protected allows any class in the same package to instantiate SingletonObject. We can easily create a class "in the same package" by specifying the corresponding package statement.
Edit: The answer of Carlos made me realize an additional problem that results from making the constructor protected as opposed to public: A subclass of the singleton class can be created (in another package), which can be freely instantiated and have its instance methods called; the singleton class itself no longer has full control over where and how instances (or 1 instance) are created.

Hiding the visibility of a class to other classes

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;
}

When and Why would a Child class declare a static instance member of the parent class?

This is another design pattern in some legacy code that I couldn't find much about on google. In this case a child class extends its abstract parent, but then turns right around and declares a static instance of the parent:
public abstract class MessageBase {
protected DAOFactory factory;
// method declarations
}
public class EDWMessage extends MessageBase {
private static MessageBase instance;
public static MessageBase getInstance(Properties properties) {
if (instance == null) {
instance = new EDWMessageTransaction(properties, null);
}
return instance;
}
//more code
}
I'm not sure I understand what would drive this design pattern (if it is a known pattern). Is this a sort of convenience pattern to avoid declaring each member variable of the parent as static? Or is it meant to allow multiple children classes to each have one instance of the parent. But if that's the case, why the excessive use of inheritance over just plain composition?
The rest of the code gives no indication as to why it would be done this way. Any thoughts or ideas would be much appreciated. Thanks!
P.S. I seem to be running in to a lot of interesting design patterns in this legacy code that I don't know how to handle. Thanks to everyone who has helped me out already.
Edit: Expanding the code sample. Will edit again as I discover someplace that actually uses this code. Yay for no documentation.
This is a common idiom for thread-safe lazy singleton initialization. If you can have a singleton class, you delegate to a private static instantiating class.
public class MySingleton{
private MySingleton(){
}
public static MySingleton getInstance(){
return SingletonCreator.INSTANCE;
}
private static class SingletonCreator{
private static final MySingleton INSTNACE = new MySingleton();
}
}
Not sure if this is how your child class is being used, but this would be a use case for a child class holding a static instance of its parent
The original intent probably was that for each subclass of MessageBase there should only be 1 instance and that you can access that instance with a commom method in the base class
so you could iterate over all message types and get the instance of each
my 2cents

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