簡體   English   中英

如何為場景確定最合適的設計模式

[英]How to identify the most suitable Design Pattern for a scenario

我想實現一個基於 GUI 的繪圖程序。 它應該能夠繪制圓形、三角形和正方形。 並且它應該能夠在未來擴展系統中的形狀數量。

該程序將為這些形狀賦予某些“能力”,例如“移動”、“擴展”、“旋轉”以及“繪制”(以在 GUI 中繪制形狀)的能力。 這些方法中的每一個都需要一個作為參數傳入的“圖形上下文”,以便繪制它們。

我想為這個程序使用一個設計模式,因為不同的形狀會有不同的方法,我認為策略模式會很有用。

我想知道我使用這種模式的方式是可以的。

interface Shape{}

interface Behavioral{
public void move(Graphics g){}
public void expand(Graphics g){}
public void draw(Graphics g){}
}

(There is an aggregation between shape and behavioral)

interface Rotatable{
public void rotate(Graphics g)
} 

interface RotatableToLeft extends Rotatable(){
public void rotate(Graphics g)
}

interface RotatableToRight extends Rotatable(){
public void rotate(Graphics g)
}

class circle implements Shape{
public void move(Shape g){--}
public void expand(Shape g){--}
public void draw(Shape g){--}

}

class Square implements Shape implements Rotatable{
public void move(Shape g){--}
public void expand(Shape g){--}
public void draw(Shape g){--}
public void rotatefree(RotatableToLeft g){--}
}

class Triangle implements Shape implements Rotatable{
public void move(Graphics g){--}
public void expand(Graphics g){--}
public void draw(Graphics g){--}
public void rotateLeft(RotatableToLeft g){--}
public void rotateRight(RotatableToRight g){--}

}

Shape應該是一個通用的抽象基類,而不是一個接口,至少, draw()應該是Shape一個成員。 而且由於每個形狀可能都實現了Behavioral所有其他方法,因此您可以擺脫Behavioral並將其所有方法移至Shape

RotatableToLeftRotatableToRight沒有任何意義。 只使用一個接口,只包含一個方法,並傳遞方向來旋轉。

您可能需要一些“tryAs”、“is”和“as”方法。 例如:

class Shape
{
    public Rotatable tryAsRotatable() { return null; }

    public final boolean isRotatable()
    {
        return tryAsRotatable() != null;
    }

    public final Rotatable asRotatable() 
    {
        Rotatable result = tryAsRotatable();
        assert result != null;
        return result;
    }
}

class Circle extends Shape implements Rotatable
{
    @Override
    public Circle tryAsRotatable() { return this; }
}

暫無
暫無

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

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