How to identify the most suitable Design Pattern for a scenario

Nishadi :

I want to implement a GUI based drawing program. It should be able to draw circles,triangles and squares. And it should be able to expand the number of shapes in the system in future.

The program will give certain ‘abilities’ to these shapes, such as the ability to ‘move’, ‘expand’ , ‘rotate’ and of course ‘draw’ (to get the shape drawn in the GUI). Each of these methods needs a ‘Graphics Context’ passed in as as a parameter, in order to get them drawn.

I want use a design pattern for this program and since there will be methods differ from shape to shape I think strategy pattern will be useful.

I want to know the way which I have used this pattern is okay.

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){--}

}
Mike Nakis :

Shape should probably be a common abstract base class, not an interface, and at the very least, draw() should be a member of Shape. And since every shape is probably to implement all other methods of Behavioral, you can get rid of Behavioral and move all of its methods to Shape.

RotatableToLeft and RotatableToRight do not make any sense. Use only one interface, containing only one method, and pass the direction to rotate.

You will probably need a few 'tryAs' and 'is' and 'as' methods. For example:

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; }
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=296267&siteId=1