2021/11/24策略模式
策略者模式
java代码
package Strategy; public class AirplaneStrategy implements TravelStrategy { @Override public void goTravel() { System.out.println("乘飞机去旅行,飞机策略"); } }
package Strategy; public class BicycleStrategy implements TravelStrategy { @Override public void goTravel() { System.out.println("骑行,骑行策略"); } }
package Strategy; public class CarStrategy implements TravelStrategy { @Override public void goTravel() { System.out.println("自驾游,自驾策略"); } }
package Strategy; public class FootStrategy implements TravelStrategy { @Override public void goTravel() { System.out.println("徒步旅行,徒步策略。"); } }
package Strategy; public class StrategyTest { public static void main(String[] args) { Traveler traveler = new Traveler(); traveler.setTravelStrategy(new AirplaneStrategy()); traveler.goTravel(); System.out.println(); traveler.setTravelStrategy(new CarStrategy()); traveler.goTravel(); System.out.println(); traveler.setTravelStrategy(new BicycleStrategy()); traveler.goTravel(); System.out.println(); traveler.setTravelStrategy(new FootStrategy()); traveler.goTravel(); System.out.println(); } }
package Strategy; public class Traveler { private TravelStrategy travelStrategy; public TravelStrategy getTravelStrategy() { return travelStrategy; } public void setTravelStrategy(TravelStrategy travelStrategy) { this.travelStrategy = travelStrategy; } public void goTravel() { travelStrategy.goTravel(); } }
package Strategy; public interface TravelStrategy { void goTravel(); }