策略模式+工厂模式:
1 public abstract class Car { 2 //汽车品牌 3 private String brand; 4 public Car(String brand) { 5 this.brand = brand; 6 } 7 public Car(String brand, MoveStrategy strategy) { 8 this.brand = brand; 9 this.moveStrategy=strategy; 10 } 11 //汽车的运行策略:使用汽油运行,使用电能运行等等 12 private MoveStrategy moveStrategy; 13 //运行方法 14 public void move() { 15 System.out.print(brand); 16 moveStrategy.move(); 17 } 18 public void setMoveStrategy(MoveStrategy moveStrategy) { 19 this.moveStrategy = moveStrategy; 20 } 21 } 22 /** 23 * 使用汽油运行的策略实现 24 */ 25 public class GasolineMoveStrategy implements MoveStrategy{ 26 @Override 27 public void move() { 28 System.out.println(" Use Gasoline Move!"); 29 } 30 } 31 /** 32 * 使用电能运行的策略实现 33 */ 34 public class ElectricityMoveStrategy implements MoveStrategy { 35 @Override 36 public void move() { 37 System.out.println(" Use Electricity Move!"); 38 } 39 } 40 41 public class TeslaCar extends Car { 42 public TeslaCar(String brand) { 43 super(brand,new ElectricityMoveStrategy()); 44 } 45 } 46 public class Client { 47 public static void main(String[] args) { 48 TeslaCar car = new TeslaCar("Tesla"); 49 car.move(); 50 car.setMoveStrategy(new GasolineMoveStrategy()); 51 car.move(); 52 } 53 } 54 55 //抽象工厂 56 public interface MoveStrategyFactory { 57 MoveStrategy create(); 58 } 59 /** 60 * 使用氢能源运行的策略工厂实现 61 */ 62 public class HydrogenMoveStrategyFactory implements MoveStrategyFactory { 63 @Override 64 public MoveStrategy create() { 65 //具体的策略实现类被隐藏 66 return new HydrogenMovetrategy(); 67 } 68 } 69 public class Client { 70 public static void main(String[] args) throws IllegalAccessException, InstantiationException, ClassNotFoundException { 71 TeslaCar car = new TeslaCar("Tesla"); 72 //工厂模式解耦,上层模块不需要知道具体的策略实现类 73 MoveStrategyFactory factory = new HydrogenMoveStrategyFactory(); 74 MoveStrategy moveStrategy = factory.create(); 75 car.setMoveStrategy(moveStrategy); 76 car.move(); 77 } 78 }
。
參考文章:
https://www.zhihu.com/question/20367734?sort=created
https://www.cnblogs.com/takumicx/p/9796601.html