概述:策略模式对应于解决某一个问题的一个算法族,允许用户从该算法族中任选一个算法解决某一问题,同时可以方便的更换算法或者增加新的算法。并且由客户端决定调用哪个算法。
例子:要读取一个文件中的一段文字,文件可能是存在于文件系统中,也可能存在于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类:
Test类:/** * 负责和具体的策略类交互 * 将具体的算和调用端分离,使得算法可以独立于客户端进行变化 */ 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(); } }
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); } }