Preface: [ Mode Overview ] ---------- by xingoo
Intention mode
Define a series of algorithms, encapsulate them, so that the algorithm is independent of the applied objects.
For example, a system has a lot of sorting algorithms, sorting algorithms but which is the object of its own customers. So we put every sort as a policy object, which object to call customers, use the corresponding strategic approach.
Scenarios
1 when many classes, not just the actions or policies at the same time, can act or policy being drawn up separately, so that the main body of the class can be unified.
2 need to use a different algorithm.
3 a class defines a variety of behaviors.
Mode structure
Context role of environmental policy caller
class Context{
private Strategy strategy;
public Strategy getStrategy() {
return strategy;
}
public void setStrategy(Strategy strategy) {
this.strategy = strategy;
}
public void operation(){
strategy.action();
}
}
Abstract Strategy strategy, provides for a single call interface
interface Strategy{
public void action();
}
ConcreteStrategy specific strategies
class ConcreteStrategy1 implements Strategy{
public void action(){
System.out.println("strategy1 oepration");
}
}
class ConcreteStrategy2 implements Strategy{
public void action(){
System.out.println("strategy2 oepration");
}
}
All codes
package com.xingoo.test.design.strategy;
class Context{
private Strategy strategy;
public Strategy getStrategy() {
return strategy;
}
public void setStrategy(Strategy strategy) {
this.strategy = strategy;
}
public void operation(){
strategy.action();
}
}
interface Strategy{
public void action();
}
class ConcreteStrategy1 implements Strategy{
public void action(){
System.out.println("strategy1 oepration");
}
}
class ConcreteStrategy2 implements Strategy{
public void action(){
System.out.println("strategy2 oepration");
}
}
public class Client {
public static void main(String[] args) {
Context ctx = new Context();
ctx.setStrategy(new ConcreteStrategy1());
ctx.operation();
ctx.setStrategy(new ConcreteStrategy2());
ctx.operation();
}
}
operation result
strategy1 oepration
strategy2 oepration
Reproduced in: https: //my.oschina.net/u/204616/blog/545084