簡體   English   中英

如何使用 Java Swing 實現責任鏈

[英]How to implement chain of responsibility with Java Swing

我的任務是創建一個簡單的繪圖應用程序,在其中可以使用 Java Swing 和 MVC 繪制帶有選擇的邊框和填充顏色的基本形狀(橢圓形、線條、矩形)。

模型的形狀部分是使用復合模式實現的。 要實現的功能是繪制(這已經由形狀類本身處理)、調整大小、移動和刪除形狀,我應該使用責任鏈 (CoR) 模式來實現這一點。

CoR 在理論上對我來說很有意義,但我很難理解如何在實踐中應用它來實現功能。 我知道當我點擊繪圖面板時,程序應該識別出選擇了哪個形狀,然后我可以實現調整大小、移動、刪除的方法。

所以我需要的建議是:

1) 如何在這里實際實現 CoR 模式?

2)什么是實現調整大小,移動,刪除功能的好方法? 在自己的具體處理程序類中,作為形狀類中的方法,其他?

非常感謝您的幫助。

這是一個提議的 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;
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM