【问题标题】:How to implement chain of responsibility with Java Swing如何使用 Java Swing 实现责任链
【发布时间】:2019-12-18 17:34:41
【问题描述】:

我的任务是创建一个简单的绘图应用程序,其中可以使用 Java Swing 和 MVC 绘制带有选择的边框和填充颜色的基本形状(椭圆形、线条、矩形)。

模型的形状部分是使用复合模式实现的。要实现的功能是绘图(这已经由形状类本身处理)、调整大小、移动和删除形状,我应该使用责任链 (CoR) 模式来实现这一点。

CoR 在理论上对我来说是有意义的,但我很难掌握如何将它应用到实践中实现功能。我知道当我点击绘图面板时,程序应该识别出哪个形状被选中,然后我可以实现调整大小、移动、删除的方法。

所以我需要的建议是:

1) 这里如何实际实现 CoR 模式?

2) 实现调整大小、移动、删除功能的好方法是什么?在自己的具体处理程序类中,作为形状类中的方法,其他?

非常感谢您的帮助。

【问题讨论】:

  • 您确定不需要(抽象)工厂或任何适合对象创建的创建模式吗?责任链是一种行为模式,一个很好的使用案例可能是 ATM。
  • 我同意使用工厂是有意义的,但是对于作业,我被指示使用复合模式作为模型部件。
  • 我对 CoR 不确定,但引用了一些相关的例子hereGraphPanel 是最简单的。

标签: java swing chain-of-responsibility


【解决方案1】:

这是一个提议的 CoR 基本实现。
为了便于使用,以下代码是一个文件 mre :整个代码可以复制粘贴到 ShapeManipulator.java 并运行:

public class ShapeManipulator {

    public static void main(String[] args) {
        Shape s1 = new Shape();
        Shape s2 = new Shape();
        Shape s3 = new Shape();

        ShapeManipulationBase move = new MoveHandler();
        ShapeManipulationBase resize = new ResizeHandler();
        ShapeManipulationBase delete = new DeleteHandler();

        move.setXparam(50).setYparam(25).handle(s1);
        resize.setXparam(100).setYparam(250).handle(s1);
        resize.setXparam(200).setYparam(20).handle(s2);
        delete.handle(s3);
    }
}

//CoR basic interface 
interface ShapeManipulationHandler {
     void handle(Shape shape);
}

//base class allows swtting of optional x, y parameters 
abstract class ShapeManipulationBase implements ShapeManipulationHandler {

    protected int Xparam, Yparam; 

    //setters return this to allow chaining of setters 
    ShapeManipulationBase setXparam(int xparam) {
        Xparam = xparam;
        return this;
    }

    ShapeManipulationBase setYparam(int yparam) {
        Yparam = yparam;
        return this;
    }

    @Override
    public abstract void handle(Shape shape) ;
}

class MoveHandler extends ShapeManipulationBase {

    @Override
    public void handle(Shape shape) {
        System.out.println("Moving "+ shape + " by X="+ Xparam + " and Y="+ Yparam);
    }
}

class ResizeHandler extends ShapeManipulationBase {

    @Override
    public void handle(Shape shape) {
        System.out.println("Resizing "+ shape + " by X="+ Xparam + " and Y="+ Yparam);
    }
}

class DeleteHandler extends ShapeManipulationBase {

    @Override
    public void handle(Shape shape) {
        System.out.println("Deleting "+ shape);
    }
}

class Shape{
    private static int shapeCouner = 0;
    private final int shapeNumber;

    Shape() {
        shapeNumber = ++shapeCouner;
    }

    @Override
    public String toString() {
        return "Shape # "+shapeNumber;
    }
}

【讨论】:

  • 谢谢,这看起来很有用,我会尝试相应的实现。
  • 这个答案中没有任何类似于责任链设计模式的东西。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-02-08
  • 1970-01-01
  • 1970-01-01
  • 2012-06-27
  • 2021-05-30
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多