设计模式之策略模式

概念

接口提供抽象策略方法,由实现类提供具体的策略,并在使用时能总体替换。bash

  • Strategy 策略接口
  • ConcreteStrategy 具体策略实现类
  • Context 上下文 用来选择具体策略

优势

  • 策略之间能够随意切换
  • 添加新策略只须要新建类,不须要修改原有代码

缺点

  • 当策略比较多时,也须要较多的实现类

实例

以出行的策略为例ide

  • 抽象策略
这里也能够用抽象类
/**
 * 策略接口
 * 提供到达目的地方法,具体怎么去由子类实现
 * @author by peng
 * @date in 2019-06-14 23:31
 */
public interface ITransportable {
    
    /**
     * 到达目的地
     */
    void toDestination(String destination);
}
复制代码
  • 具体策略
public class Car implements ITransportable {
    @Override
    public void toDestination(String destination) {
        System.out.println("坐车去。。。" + destination);
    }
}

public class Plane implements ITransportable {
    @Override
    public void toDestination(String destination) {
        System.out.println("坐飞机去。。。" + destination);
    }
}
复制代码
  • 执行策略的类
public class Person {
    private ITransportable transportable;
    public void setTransportable(ITransportable transportable){
        this.transportable = transportable;
    }
    
    public void travel(String destination){
        transportable.toDestination(destination);
    }
}
复制代码
  • 测试
public class Test {
    public static void main(String... arg){
        Person ming = new Person();
        ming.setTransportable(new Car());
        ming.travel("北京");
        ming.setTransportable(new Plane());
        ming.travel("上海");
    }
}

结果: 能够在使用策略时,随时切换策略。
坐车去。。。北京
坐飞机去。。。上海
复制代码
相关文章
相关标签/搜索