I have a class called Timeline. I want to allow several defaults in my code, such as a Timeline with a Start event (The details are not needed. All that matters is that I have a class, and I want to be able to have a few different default setting). Here are the options I thought of:1) Following a GUI/Swing inspired idea, I might want to subclass the Timeline class and, in its constructor, use the public functions to set the default. Then, I could later just instantiate those objects instead of the superclass2) A factory class could have functions like getTimeLineWithExplosion and set everything up.Which of those two is the better idea? Is there a design pattern better than both of them?PS: This is implemented in Java, but could easily be in another language.
Subclassing to change default settings?
java;design;design patterns;object oriented
About your options. I don't think subclassing here is a good idea. As I see you don't follow the is - a relationship here. If they have slightly different defaults - than it is different objects of the same class, but not different classes, since they don't have different behavior.Factory option looks much better. You don't need to create new class for each new defaults you want. And factory abstracts the underlying logic nicely.I propose you another idea. Implement something like Builder pattern, to achive constructions like this:createTimeline().withStartEvent().build()orcreateTimeline().withStartEvent().withAnotherDefault(def).andWithSomeAddition(42).build()I don't know Java well, but I sure this could be implemented, and won't be significantly harder then factory, but readability would be better (as for me).If Java allows a way to declare implicit type conversions - you could end up without that build() call