设计模式——策略模式

概述:策略模式对应于解决某一个问题的一个算法族,允许用户从该算法族中任选一个算法解决某一问题,同时可以方便的更换算法或者增加新的算法。并且由客户端决定调用哪个算法。


例子:要读取一个文件中的一段文字,文件可能是存在于文件系统中,也可能存在于classpath的路径中,这时就可以定义两种资源的读取策略,由客户端选择具体用哪个策略。

Strategy类(策略类接口):
public interface Strategy {

    public String readString() throws IOException;

}
FileSystemStrategy (文件系统读取策略):
public class FileSystemStrategy implements Strategy {

    private String path;

    public FileSystemStrategy(String path) {
        this.path = path;
    }

    @Override
    public String readString() throws IOException {

        StringBuilder builder = new StringBuilder();
        FileReader fr = new FileReader(path);
        BufferedReader bfr = new BufferedReader(fr);
        String line = null;
        while ((line=bfr.readLine()) != null) {
            builder.append(line + "\r\n");
        }
        bfr.close();

        return builder.toString();
    }
}

ClasspathStrategy类(classpath路径读取策略):
public class ClasspathStrategy implements Strategy {

    private String path;

    public ClasspathStrategy(String path) {
        this.path = path;
    }

    @Override
    public String readString() throws IOException {

        InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream(path);
        InputStreamReader isr = new InputStreamReader(inputStream);

        StringBuilder builder = new StringBuilder();
        BufferedReader bfr = new BufferedReader(isr);
        String line = null;
        while ((line=bfr.readLine()) != null) {
            builder.append(line + "\r\n");
        }
        bfr.close();
        return builder.toString();
    }
}
Context类:
/**
 * 负责和具体的策略类交互
 * 将具体的算和调用端分离,使得算法可以独立于客户端进行变化
 */
public class Context {

    private Strategy strategy;

    public Context(Strategy strategy) {
        this.strategy = strategy;
    }

    public void setStrategy(Strategy strategy) {
        this.strategy = strategy;
    }

    public String readString() throws IOException {
        return strategy.readString();
    }
}
Test类:
public class Test {

    public static void main(String[] args) throws IOException {

        Strategy strategy1 = new FileSystemStrategy("C://1.txt");
        Strategy strategy2 = new ClasspathStrategy("1.txt");

        Context context = new Context(strategy1);

        String str = context.readString();

        System.out.println(str);
    }
}




  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值