策略设计模式

时间:2022-07-27 21:59:13

策略设计 

 * 策略模式定义了一系列的算法,并将每一个算法封装起来,而且使他们还可以相互替换。策略模式让算法独立于是用它的客户而独立变化。

/**
 * 回家策略接口
 * @author dell
 *
 */
public interface GoHomeStrategy {


public String goHomeByWhat();
}


package Strategy;


public class AFewPeople  implements GoHomeStrategy {

@Override
public String goHomeByWhat() {
return "乘飞机回家!!!";
}

}


package Strategy;


public class MiddleFewPeople  implements GoHomeStrategy {
@Override
public String goHomeByWhat() {
return "乘火车回家!!!";
}
}

package Strategy;


public class MorePeople  implements GoHomeStrategy {
@Override
public String goHomeByWhat() {
return "乘汽车回家!!!";
}
}


package Strategy;


public class PeopleGoHome {
private GoHomeStrategy  strategy;
public PeopleGoHome(GoHomeStrategy strategy) {
super();
this.strategy = strategy;
};
public String getGoHomeStrategy(){
return strategy.goHomeByWhat();
}
}

package Strategy;


/**
 * 策略模式定义了一系列的算法,并将每一个算法封装起来,而且使他们还可以相互替换。策略模式让算法独立于是用它的客户而独立变化。
 * @author dell
 *
 */
public class ClientTest {


public static void main(String[] args) {
GoHomeStrategy s1 = new MorePeople();// 封装起来的算法,完全独立于客户端

PeopleGoHome  pg = new PeopleGoHome(s1);// 调用算法策略
System.out.println(pg.getGoHomeStrategy());

GoHomeStrategy s2 = new MiddleFewPeople();
PeopleGoHome  pg2 = new PeopleGoHome(s2);
System.out.println(pg2.getGoHomeStrategy());

GoHomeStrategy s3 = new AFewPeople();
PeopleGoHome  pg3 = new PeopleGoHome(s3);
System.out.println(pg3.getGoHomeStrategy());
}
}