策略模式的使用情景
最近在做一個(gè)比賽芭碍,由于算法肯定有多種董瞻,但是還沒有確定具體有哪些策略,所以不知道還要寫什么東西峻村,所以采用了策略+簡(jiǎn)單工廠的設(shè)計(jì)模式麸折。策略模式可以處理在不同時(shí)間應(yīng)用不同的業(yè)務(wù)規(guī)則的這種變化性。
類圖
算法的簡(jiǎn)略類圖
實(shí)現(xiàn)
interface Algorithm{
int getAction(int index);
}
class AlgorithmAImpl implements Algorithm{
@Override
public int getAction(int index) {
return index+1;
}
}
class AlgorithmBImpl implements Algorithm{
@Override
public int getAction(int index) {
return index+2;
}
}
class AlgorithmManager{
Algorithm mAlgorithm;
int type;
int getRes(int type){
this.type = type;
switch (type){
case 0:
mAlgorithm = new AlgorithmAImpl();
break;
case 1:
mAlgorithm = new AlgorithmBImpl();
break;
default:
break;
}
return getAction(type);
}
private int getAction(int index){
return mAlgorithm.getAction(index);
}
}