samedi 30 avril 2022

Template method pattern with subclasses that have different methods

Let's consider two objects that have a lot in common, but that differ on some minor points and therefore both need to have their own method:

public class ParentClass{

    private int var1, var2, ..., varN; // many variables in common

    public int method1(){ ... };
    [...]
    public int methodN(){ ...}; // many methods in common

}

public class ChildClass1 extends ParentClass{

   // no exclusive variable

    public void specificMethod1(){ ... }; // specific method

}

public class ChildClass2 extends ParentClass{

    // no exclusive variable

    public void specificMethod2(){ ... }; // specific method

}

Is there a "standard" way to deal with such problems? I am currently learning design patterns so I thought that template method could be useful here by doing something like that:

public class ParentClass{

    private int var1, var2, ..., varN; // many variables in common

    public int method1(){ ... };
    [...]
    public int methodN(){ ...}; // many methods in common

    public abstract void specificMethod1(); // specific method
    public abstract void specificMethod2(); // specific method

}

public class ChildClass1 extends ParentClass{

    @Override
    public void specificMethod1(){

        // implementation
    }

    @Override
    public void specificMethod2(){
        
        throw new RuntimeException("this method can only be used by ChildClass2!");
    }

}

public class ChildClass2 extends ParentClass{

    // Same here but implements specificMethod2 and throw exception in specificMethod1

}

Is that a good way of dealing with the problem? Is there another design pattern that suits better here? Or even just another approach that I didn't think about?

EDIT: Of course, I could declare every specific method in the associated child class, but at compile time, I have no idea whether I will need the first or the second class (and I am sure that dynamic casting is not a good idea here neither), therefore I am using the parent class everywhere.

Aucun commentaire:

Enregistrer un commentaire