我们需要画一个图形,可选的策略就是用红色笔来画,还是绿色笔来画,或者蓝色笔来画。
首先,先定义一个策略接口:
1 2 3
| public interface Strategy { void draw(int radius, int x, int y); }
|
然后我们定义具体的几个策略:
1 2 3 4 5 6
| public class RedPen implements Strategy { @Override public void draw(int radius, int x, int y) { System.out.println("用红色笔画图,radius:" + radius + ", x:" + x + ", y:" + y); } }
|
1 2 3 4 5 6
| public class GreenPen implements Strategy { @Override public void draw(int radius, int x, int y) { System.out.println("用绿色笔画图,radius:" + radius + ", x:" + x + ", y:" + y); } }
|
1 2 3 4 5 6
| public class BluePen implements Strategy { @Override public void draw(int radius, int x, int y) { System.out.println("用蓝色笔画图,radius:" + radius + ", x:" + x + ", y:" + y); } }
|
使用策略的类:
1 2 3 4 5 6 7 8 9 10 11
| public class Context { private Strategy strategy;
public Context(Strategy strategy) { this.strategy = strategy; }
public void executeDraw(int radius, int x, int y) { strategy.draw(radius, x, y); } }
|
客户端演示:
1 2 3 4 5 6
| public class Main { public static void main(String[] args) { Context context = new Context(new BluePen()); context.executeDraw(10, 0, 0); } }
|
output:
1
| 用蓝色笔画图,radius:10, x:0, y:0
|
参考