class A{ public void doAction(int type){ .......//其他代码 if(type ==0){ do action0; return; } if(type ==1){ do action1; return; } if(type ==2){ do action2; return; } ... if(type ==n){ do action4; return; } .......//其他代码 } }
client: new A().doAction(0);
interface Action{ do(); }
class Action0 implements Action{ do(){实现action0操作} } class Action1 implements Action{ do(){实现action1操作} } class Action2 implements Action{ do(){实现action2操作} } 。。。
class A{ Action action = null; setAction(Action action){this.action = action;} doAction(){ ... action.do(); ... } }
client:在使用A时动态设置其Action对象。 A a =new A(); a.setAction(new Action0()); //动态设置其Action对象 a.doAction();
原文:https://www.cnblogs.com/onetwothree/p/10191839.html