一、UML图
Context:上下文角色,屏蔽上层模块对下层策略、算法的直接访问,封装算法的多变性。
Strategy:抽象策略角色,对策略的抽象。
ConcreteStrategy:具体策略类,算法的具体实现,继承或实现Strategy。
二、实例
1、Context
package com.designPattern.strategy;
/**
* Created by ZhangJintao on 2020/3/8.
*/
public class TransportationContext {
private Transportation transportation;
public TransportationContext(Transportation transportation) {
this.transportation = transportation;
}
public void showTransportation(){
this.transportation.show();
}
}
2、 Strategy
package com.designPattern.strategy;
/**
* Created by ZhangJintao on 2020/3/8.
*/
public abstract class Transportation {
public abstract void show();
}
3、ConcreteStrategy
package com.designPattern.strategy;
/**
* Created by ZhangJintao on 2020/3/8.
*/
public class ByBicycle extends Transportation {
@Override
public void show() {
System.out.println("我是自行车,健康环保。绿色出行,从我做起。");
}
}
package com.designPattern.strategy;
/**
* Created by ZhangJintao on 2020/3/8.
*/
public class ByCar extends Transportation {
@Override
public void show() {
System.out.println("我是小汽车,百公里只需6个油。想去哪里就去哪里,欧耶!");
}
}
4、main
package com.designPattern.strategy;
/**
* Created by ZhangJintao on 2020/3/8.
*/
public class main {
public static void main(String[] args) {
TransportationContext transportationContext = new TransportationContext(new ByBicycle());
transportationContext.showTransportation();
transportationContext = new TransportationContext(new ByCar());
transportationContext.showTransportation();
}
}