java template design
Posted
by
Sean Nguyen
on Stack Overflow
See other posts from Stack Overflow
or by Sean Nguyen
Published on 2011-01-09T22:48:46Z
Indexed on
2011/01/09
22:54 UTC
Read the original article
Hit count: 171
java
Hi, I have this class:
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 do the similar things and delegate the actual work to the approriate class. But I also want to easily extends this frame work without changing the template. So 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 doesn't work. Can anybody suggest me a better way to do that? 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 number of extended class.
Thanks,
© Stack Overflow or respective owner