Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Template method pattern with implementation specific parameter type

I often get into situation when I'd like to use template method pattern, but the template method expects a different type of a parameter, like this:

public abstract class AbstractFoo  {

    public void process(TypeA a, TypeB b) {

     //do common processing
        if (b == null) {
          doProcess(a);
        } else if(a == null) {
          doProcess(b);
        }
    }

    public abstract void doProcess(TypeA a);
    public abstract void doProcess(TypeB b);
}

This doesn't look good. One of the supplied paramaters would have to be null and all services would have to implement dummy doProcess methods for other types. Is there any better pattern for this? How do you deal with this ? I don't want to use constructor because these services are spring beans. Also the same problem applies to Strategy pattern.

like image 365
lisak Avatar asked Feb 23 '23 13:02

lisak


2 Answers

public abstract class AbstractFoo<T>  {

    public void process(T a) {

        //do common processing

        doProcess(a);
    }

    protected abstract void doProcess(T a);
}

public class Person extends AbstractFoo<Person> {
    @Override
    protected void doProcess(Person p) {
        p.draw();
    }
}


public class Car extends AbstractFoo<Car> {
    @Override
    protected void doProcess(Car c) {
        c.draw();
    }
}
like image 131
Boris Pavlović Avatar answered May 11 '23 08:05

Boris Pavlović


You're right that it definitely isn't a template method pattern, but I'm not sure exactly what you're trying to do. Maybe you're after the factory pattern:

interface Foo {
    boolean isA();
    boolean isB();
    ...
}

class ProcessorFactory {
    public Processor getProcessor(Foo foo) {
        if (foo.isA()) {
            return new AProcessor();
        }
        if (foo.isB()) {
            return new BProcessor();
        }
        ...
    }
}

As for constructors, all of my spring beans have constructors that express their dependencies. What's wrong with that?

like image 32
Ryan Stewart Avatar answered May 11 '23 08:05

Ryan Stewart