I want to force implementation of the singleton pattern on any of the extended classes of my parent class. That is, I only want one instance of every child class to ever be around (accessible through Child.INSTANCE or something like this).
Ideally what I would like would be for the Child.INSTANCE object to be made, and then no other object of type Parent to be made.
Currently I get my instances through something like:
public class Child extends Parent {
public static final Child INSTANCE = new Child();
....
I wonder, can a java class be made static or something in some way?
Thanks =]
Is the set of your child classes fixed? If so, consider using an enum
.
public enum Parent {
CHILD1 {
// class definition goes here
},
CHILD2 {
// class definition goes here
};
// common definitions go here
}
Since the OP mentioned about state pattern, here are two examples of enum
-based state machines: a simple one and a complex one.
It can be done, but I don't see the point. You would be better off using an enum IMHO.
enum {
Singleton,
Child { /* override methods here * }
}
However to answer you question, you could do the following
class SingletonParent {
private static final Set<Class> classes = new CopyOnArraySet();
{ if (!classes.add(getClass()) throw new AssertionError("One "+getClass()+" already created."); }
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With