For the GUI of a program, I want it to list several items, all of which are, from a programming side, just subclasses. They can add one of these items to a list. I don’t want to hard-code which subclasses there are. What would be the best way to allow the GUI to know about the subclasses, only having the base class to refer to?
2
@Andrew Timson (+1) makes a superb point about the use of reflection (if possible) and using an interface.
From an Object Oriented Design point of view, Interface’s are going to be a much nicer way to go – unless of course there is enough logic in common/inherited to warrant subclassing. This could be argued as part of the “Dependency Inversion Principle” at work; “Depend upon Abstractions. Do not depend upon concretions.”. You’re already leaning towards quite a clean solution that adheres to this by avoiding the hard coding though, so nice one!
In addition to that, Reflection could be the way to go. There’s some more information on when reflection should be used over here, on StackOverflow
Other than that, you could use something like an adapted Observer Pattern and have each new instance of a given sub-class “register” itself upon initialisation. So there is an object you can query to get all of the objects in question; you could make this a Singleton to ensure it’s always accessible throughout the lifecycle of the application – and to make sure there is only ever one object to query.
That’s not the neatest solution, but it is another one that could work.
1
First off: I think in this case, rather than populating the list with a class/subclasses of it, using some sort of interface may be the more appropriate design.
The best approach is probably going to depend on your language. If it supports reflection (like C# or Java), you may be able to look for other classes that subclass/implement your interface.
If it doesn’t – or if you want a simpler solution – you can simply keep the list of available types in some sort of configuration file/table that gets read in at runtime.
you can do this:
import java.util.*;
class Super {
Super() {
subclasses.add(getClass());
}
static List<Object> subclasses=new LinkedList<Object>();
}
class Sub1 extends Super {
}
class Sub2 extends Super {
}
public class P205597 {
public static void main(String[] args) {
new Sub1();
new Sub2();
System.out.println(Super.subclasses);
}
}
4