Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Static/Final java classes?

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 =]

like image 572
Dartoxian Avatar asked Dec 21 '22 19:12

Dartoxian


2 Answers

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.

like image 189
Chris Jester-Young Avatar answered Dec 24 '22 09:12

Chris Jester-Young


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."); }
}
like image 30
Peter Lawrey Avatar answered Dec 24 '22 10:12

Peter Lawrey