It depends. In your case, there isn't one. But usually you would solve this by some form of polymorphism or Template Method pattern. But your data model doesn't seem to have been designed in such a way, so you're pretty much screwed, and you'll have to make an ugly nested IF structure. Alternatively you can refactor it slightly and use a Template Method Pattern. In this scenario you could use a Factory method pattern to create different templates based on the String, each of these templates would thn have a different TemplateMethod()
which would be invoked. This allows you to treat all object equally, yet have one part (the template method) act independently.
For a more in-depth explanation, see: http://en.wikipedia.org/wiki/Template_method_pattern
Edit: Added example, of less shitty Factory method.
TemplateFactory.java
public class TemplateFactory {
private Map<String, Class> map;
public TemplateFactory() {
this.map = new TreeMap<>();
map.put("Template 1", Template1.class);
map.put("Template 2", Template2.class);
}
public BaseTemplate createBaseTemplate(String comparison)
{
if (!map.containsKey(comparison))
{
return null;
}
try {
return (BaseTemplate) map.get(comparison).getConstructor().newInstance();
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
} catch (NoSuchMethodException e) {
e.printStackTrace();
}
return null;
}
public static void main(String[] args) {
TemplateFactory tf = new TemplateFactory();
BaseTemplate t1 = tf.createBaseTemplate("Template 1");
BaseTemplate t2 = tf.createBaseTemplate("Template 2");
System.out.println(t1.templateMethod(""));
System.out.println(t2.templateMethod(""));
}
}
BaseTemplate.java
public abstract class BaseTemplate {
public String doSomething()
{
// whatever
return "Hello";
}
public int anotherRealMethod(String data)
{
//also whatever
return 0;
}
public abstract String templateMethod(String data);
}
Template1.java
public class Template1 extends BaseTemplate {
@Override
public String templateMethod(String data) {
return "Template 1";
}
}
Template 2.java
public class Template1 extends BaseTemplate {
@Override
public String templateMethod(String data) {
return "Template 2";
}
}