java模板设计

Sea*_*yen 3 java

public class Converter
{
    private Logger logger = Logger.getLogger(Converter.class);
    public String convert(String s){ 
         if (s == null) throw new IllegalArgumentException("input can't be null");
         logger.debug("Input = " + s);
         String r = s + "abc";
         logger.debug("Output = " + s);
         return r;
    }

    public Integer convert(Integer s){
         if (s == null) throw new IllegalArgumentException("input can't be null");
         logger.debug("Input = " + s);
         Integer r = s + 10;
         logger.debug("Output = " + s);
         return r;
    }
}
Run Code Online (Sandbox Code Playgroud)

以上两种方法非常相似,所以我想创建一个模板来做类似的事情并将实际工作委托给approriate类.但我也希望在不更改模板的情况下轻松扩展此框架工作.例如:

public class ConverterTemplate
{
    private Logger logger = Logger.getLogger(Converter.class);
    public Object convert(Object s){ 
         if (s == null) throw new IllegalArgumentException("input can't be null");
         logger.debug("Input = " + s);
         Object r = doConverter();
         logger.debug("Output = " + s);
         return r;
    }

    protected abstract Object doConverter(Object arg);
}

public class MyConverter extends ConverterTemplate
{
    protected String doConverter(String str)
    {
       String r = str + "abc";
       return r;
    }

    protected Integer doConverter(Integer arg)
    {
       Integer r = arg + 10;
       return r;
    }
}
Run Code Online (Sandbox Code Playgroud)

但这不起作用.任何人都可以建议我更好的方法吗?我想实现2个目标:1.一个可扩展的模板,并为我完成所有类似的工作.我尽量减少扩展课程的数量.

谢谢,

pad*_*dis 5

使用泛型,使转换方法最终(因此当您想保留此模板时不会覆盖它)并在单独的类中为每种类型生成转换器:

public interface Converter<T> {

    public T convert(T s);
}


public abstract class AbstractConverter<T> implements Converter<T> {

    @Override
    public final T convert(T s) {
         if (s == null) throw new IllegalArgumentException("input can't be null");
         //logger.debug("Input = " + s);
         T r = doConverter(s);
         //logger.debug("Output = " + s);
         return r;
    }

    public abstract T doConverter(T s);
}


public class StringConverter extends AbstractConverter<String> {

    public String doConverter(String s) {
        String r = s + "abc";
        return r;
    };
}

public class IntegerConverter extends AbstractConverter<Integer> {

    public Integer doConverter(Integer s) {
        Integer r = s + 10;
        return r;
    };
}
Run Code Online (Sandbox Code Playgroud)