Java – template method pattern with implementation specific parameter types

I often encounter this situation when I want to use the template method mode, but the template method requires different types of parameters, as shown below:

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);
}

It doesn't look very good One of the provided parameters must be null, and all services must implement virtual doprocess methods for other types Is there a better model? What do you do with this? I don't want to use constructors because these services are spring beans The same question applies to the strategic model

Solution

public abstract class AbstractFoo<T>  {
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();
    }
}
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>