简体   繁体   中英

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

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."); }
}

You are looking at the wrong design pattern.

Take a look at the Factory pattern. A factory can create a single instance of a class and then hand it out to anyone who wants it. The factory can hand out a singleton of the parent, any child, or anything else you want.

You can use a Java enum . Basically it makes a bunch of public static classes (like you do) but puts a few restrictions on them.

public enum Child {
   INSTANCE;
}

Note that enums are full classes, so you can easily add methods on a per-instance basis if you wish.

I will answer with a question I asked a while back that was very similar. I believe that this will do what you want it to do, but comes with all the restrictions mentioned in the answers.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM