Java static / final classes?

I want to force a singleton pattern implementation for any of the extended classes of my parent class. That is, I only need one instance of each child class (accessible via Child.INSTANCE or something like this).

Ideally, what I would like to do for a Child.INSTANCE object, and then there will be no other object of type Parent.

I am currently getting my instances through something like:

public class Child extends Parent { public static final Child INSTANCE = new Child(); .... 

I wonder if the java class can become static or something in some way?

Thanks =]

+4
source share
5 answers

Is the set of your child classes fixed? If so, consider using enum .

 public enum Parent { CHILD1 { // class definition goes here }, CHILD2 { // class definition goes here }; // common definitions go here } 

Since the OP mentions a state template, here are two examples of state states based on enum : simple and complex .

+9
source

This can be done, but I do not see the point. You would be better off using enum IMHO.

 enum { Singleton, Child { /* override methods here * } } 

However, to answer your question, you can do the following

 class SingletonParent { private static final Set<Class> classes = new CopyOnArraySet(); { if (!classes.add(getClass()) throw new AssertionError("One "+getClass()+" already created."); } } 
+1
source

You are looking at the wrong design template.

Take a look at the Factory template. A Factory can create one instance of a class and then pass it on to anyone who wants it. Factory can pass a single singlet to the parent, any child, or anything else you want.

+1
source

You can use Java enum . This basically creates a bunch of public static classes (like you), but imposes a few restrictions on them.

 public enum Child { INSTANCE; } 

Note that enums are complete classes, so you can easily add methods based on each instance if you want.

0
source

I will answer using the question I asked a while ago, which was very similar. I believe that this will do what you want, but with all the limitations mentioned in the answers.

0
source

Source: https://habr.com/ru/post/1334090/


All Articles