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;
}
}
The above 2 methods are very similar, so I want to create a template to perform similar actions and delegate the actual work to the approriate class. But I also want to easily expand this frame work without changing the template. For example:
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;
}
}
But that does not work. Can someone suggest me a better way to do this? I want to achieve 2 goals: 1. A template that is extensible and does all the similar work for me. 2. I ant to minimize the amount of extended class.
Thank,
source
share