策略模式
什么是策略模式????
背景:博主我明天要去远方流浪(GoFarAway),我需要乘坐交通工具(TransportStrategy)到达目的地,有两种方式:1.自行车2.的士
**策略模式:**我选择自行车或者的士就是一种策略
**策略模式组成:**抽象策略模式(TransportStrategy),具体策略模式(TaxiStrategyImpl,BikeStrategyImpl),环境角色(GoFarAway)
//去远方
public interface GoFarAway {
void use(TransportStrategy strategy);
}
//可选择的交通工具接口
public interface TransportStrategy {
void byTransport();
}
//第一种交通工具 Taxi
public class TaxiStrategyImpl implements TransportStrategy{
@Override
public void byTransport() {
System.out.println("我将坐的士前去");
}
}
//第二种交通工具 Bike
public class BikeStrategyImpl implements TransportStrategy {
@Override
public void byTransport() {
System.out.println("我将骑自行车前去");
}
}
//测试
public class Main {
public static void main(String[] args) {
TransportStrategy tranStrategy = new TaxiStrategyImpl();
GoFarAway goFarAway = (strategy) -> strategy.byTransport();//看不懂这句话的可以访问https://blog.youkuaiyun.com/qq_25848311/article/details/100807517 着重看lambda表达式
goFarAway.use(tranStrategy);
}
}
总之一句话:定义一个Strategy接口,定义它的多个实现类,每个实现类是一种策略。
在使用时用上转型即可。