策略模式定义了算法族,分别封装起来,让它们之间可以相互替换,此模式让算法的变化独立于使用算法的客户。
duck
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
| @Data public abstract class Duck {
FlyBehavior flyBehavior;
public Duck() { }
public void performFly() { flyBehavior.fly(); } public void swim() { System.out.println("All ducks float, even decoys!"); } }
|
定义一组飞行行为
飞行接口
1 2 3 4
| public interface FlyBehavior {
public void fly(); }
|
FlyWithWings
1 2 3 4 5 6 7 8
| public class FlyWithWings implements FlyBehavior {
@Override public void fly() { System.out.println("I'm flying!!"); }
}
|
FlyRocketPowered
1 2 3 4 5 6 7 8
| public class FlyRocketPowered implements FlyBehavior {
@Override public void fly() { System.out.println("I'm flying with a rocket!"); }
}
|
具体Duck 实现类
1 2 3 4 5 6 7 8 9 10 11
| public class MallardDuck extends Duck {
public MallardDuck() {
flyBehavior = new FlyWithWings(); }
public void display() { System.out.println("I'm a real Mallard duck"); } }
|
test
1 2 3 4 5 6 7 8 9
| @GetMapping("/duck") public RestResponse<Object> duck() {
Duck duck=new MallardDuck(); duck.performFly(); duck.setFlyBehavior(new FlyRocketPowered()); duck.performFly(); return RestResponse.success(); }
|
1 2
| I'm flying!! I'm flying with a rocket!
|