I just answered another question (Select method based on field in class), and I was wondering if the pattern had a name.
Call action.applyX(a)
, where X
depends on some property of a
(e.g. type
in the example), so you instead call a.apply(action)
and let a
(or Type
) call the appropriate applyX
.
Is there a name for that?
public enum Type {
INTEGER {
@Override
public void apply(Action action, A a) {
action.applyInteger(a);
}
},
STRING {
@Override
public void apply(Action action, A a) {
action.applyString(a);
}
};
public abstract void apply(Action action, A a);
}
public interface Action {
public void applyInteger(A a);
public void applyString(A a);
}
public class A {
private Type type;
...
public void apply(Action action) {
this.type.apply(action, this);
}
}
Update
The above is just an example, and using type
as the selector is not the important part.
The selection criteria for deciding which X
method to call can be anything. In a dice game, X
could be 'Odd' or 'Even' and class A
could be 'Dice' with a 1-6 int
value.
The example is using abstract enum
methods as a way to avoid a switch
statement (less error prone). The abstract method implementations are a kind of switching technology, in this case the way to choose the appropriate X
.
Update 2
This question is about the pattern used to avoid switch statements for doing "action" logic outside of the class (A
), not about changing the behavior of A
(strategy/policy), where the "switch choices" are well defined, e.g. as a type enum (example above), or by well-known subclasses of A.
As an example, A
could define a table column. The class should not be tightly coupled to implementation code, but there will be many different implementation methods ("Actions") that must process column types differently.
Actions might be a call to the appropriate getXxx
method on ResultSet
, call the appropriate setXxx
method on PreparedStatement
, format the value for display, render it the XML or Json, parse the value, ...
All these methods would either need a switch
statement, or they could implement an interface with the "typed" methods, and ask the class "please call the right one for me".
This question is becoming pretty long. Sorry if I'm not stating the pattern clearly.