策略模式将算法独立出来,使得客户可以自由的组合各种算法。
策略模式类图
Context中维护一个算法公共接口,调用时,则根据具体的算法实现执行。
Strategy算法接口,concreteStrategy具体算法实现
以下程序演示旅行策略
//算法接口
public interface Travel {
void travel();
}
//算法实现
public class FootTravel implements Travel {
@Override
public void travel() {
System.out.println("徒步旅行");
}
}
public class BusTravel implements Travel {
@Override
public void travel() {
System.out.println("做巴士去游玩");
}
}
public class AirTravel implements Travel {
@Override
public void travel() {
System.out.println("做飞机旅游");
}
}
public class Plan {
Travel travel;
public Plan(Travel travel) {
this.travel = travel;
}
public void makePlan() {
travel.travel();
}
}
//简单工厂模式创建对象
public class TravelFactory {
public static Travel getTravelStyle(int distance) {
Travel travel;
if (distance < 10) {
travel = new FootTravel();
} else if (distance < 200) {
travel = new BusTravel();
} else {
travel = new AirTravel();
}
return travel;
}
}
//测试
public class StrategyTest {
public static void main(String[] args) {
//从工厂里面拿到对象,只要输入距离,出行方式那是旅游公司的事
Travel travelStyle = TravelFactory.getTravelStyle(30);
Plan plan = new Plan(travelStyle);
plan.makePlan();
}
}
//结果:
做巴士去游玩
网友评论