Chill
Chill

Reputation: 1113

Is there a design pattern to force initialization of a subclass implemented method?

I'm trying to create an abstract class in Java where part of its creation involves calling an initialization method that the subclass needs to implement. I want the subclass to have access to arbitrary parameters, however, that the abstract class doesn't need to know about.

Here's some code to make it more clear:

public abstract class NormalizedRandom<T> {

    private Queue<T> randomList;
    private List<T> usedRandomsList;

    public NormalizedRandom() {
        randomList = new LinkedList<T>();
        usedRandomsList = new ArrayList<T>();
        init();
        shuffleList();
    }

    protected abstract void init();

    ...

}

And

public class NormalizedRandomIntegerRange extends NormalizedRandom<Integer> {

    private int min;
    private int max;
    private int repeats;

    public NormalizedRandomIntegerRange(int min, int max, int repeats) {
        this.min = min;
        this.max = max;
        this.repeats = repeats;
    }

    @Override
    protected void init() {
        for(int num = min; num <= max; num++) {
            for(int i = 0; i < repeats; i++) {
                super.addRandomOutcome(num);
            }
        }
    }
}

Obviously this isn't going to work because super() needs to get called before I can initialize the parameters.

This sort of problem looks like there has to be some easy design pattern to solve it. I just can't think of the right way to solve it offhand.

Upvotes: 1

Views: 348

Answers (2)

JacksOnF1re
JacksOnF1re

Reputation: 3512

Try to roll out the initialization into an own class or interface, that the subclass has to provide the superclass as an argument for the constructor. Now you can easily switch and redifine the init method and the super class can call it itself, before the subclass code will run. The initStrategy can be initialized with arguments, that are not known from the superclass. I would use an interface. (I think you already know it, but it is a type of strategy pattern).

Hope this helps, Steve.

Upvotes: 1

XaviMuste
XaviMuste

Reputation: 304

I think you could use a ´Builder´ which is the creational pattern used to avoid having many different constructors. I mean getting the initialitation of the Objects out of the contructor.Using a Builder Class for that purpose.

Upvotes: 0

Related Questions