命令模式:一种数据驱动的设计模式也属于行为型模式,请求以命令的形式包裹在对象中,并传给调用对象。调用对象寻找可以处理该命令的合适的对象,并把该命令传给相应的对象,该对象执行命令。你认为是命令的地方都可以使用命令模式。
还是以绘制三角形、圆形、矩形为例:
-
- //抽象命令
- public interface Drawing {
- void execute();
- }
- //接收者
- public class Draw {
-
- public void triangle(){
- //绘制三角形逻辑
- }
- public void circular(){
- //绘制圆形逻辑
- }
- public void rectangle(){
- //绘制矩形逻辑
- }
-
- }
- //具体绘制三角形命令
- public class TriangleDraw implements Drawing {
-
- Draw draw;
-
- public TriangleDraw(Draw draw) {
- this.draw = draw;
- }
-
- @Override
- public void execute() {
- draw.triangle();
- }
- }
绘制圆形具体命令
- //具体绘制圆形命令
- public class CircularDraw implements Drawing{
-
- Draw draw;
-
- public CircularDraw(Draw draw) {
- this.draw = draw;
- }
-
-
- @Override
- public void execute() {
- draw.circular();
- }
- }
绘制矩形具体命令
- //具体绘制矩形命令
- public class RectangleDraw implements Drawing{
-
- Draw draw;
-
- public RectangleDraw(Draw draw) {
- this.draw = draw;;
- }
-
- @Override
- public void execute() {
- draw.rectangle();
- }
- }
- //使用示例
- public static void main(String[] args) {
-
- Draw draw = new Draw();
-
- TriangleDraw triangleDraw = new TriangleDraw(draw);
- CircularDraw circularDraw = new CircularDraw(draw);
- RectangleDraw rectangleDraw = new RectangleDraw(draw);
-
- Canvas canvas = new Canvas();
- canvas.takeDrawing(triangleDraw);
- canvas.takeDrawing(circularDraw);
- canvas.takeDrawing(rectangleDraw);
-
- canvas.call();
- }