Shape Fa# Shape Factory 497

Question

Factory is a design pattern in common usage. Implement a ShapeFactory that can generate correct shape.

You can assume that we have only tree different shapes: Triangle, Square and Rectangle.

Example

ShapeFactory sf = new ShapeFactory();

Shape shape = sf.getShape("Square");

shape.draw();


| |

| |

shape = sf.getShape("Triangle");

shape.draw();

/\ / \ /__\

shape = sf.getShape("Rectangle");

shape.draw();


| |

Solution

子类函数的重载(override)。注意转义字符。

代码如下:

/**
 * Your object will be instantiated and called as such:
 * ShapeFactory sf = new ShapeFactory();
 * Shape shape = sf.getShape(shapeType);
 * shape.draw();
 */
interface Shape {
    void draw();
}

class Rectangle implements Shape {
    // Write your code here
    public void draw(){
        System.out.println(" ---- ");
        System.out.println("|    |");
        System.out.println(" ---- ");
    }
}

class Square implements Shape {
    // Write your code here
    public void draw(){
        System.out.println(" ---- ");
        System.out.println("|    |");
        System.out.println("|    |");
        System.out.println(" ---- ");
    }
}

class Triangle implements Shape {
    // Write your code here
    //注意转义字符
    public void draw(){
        System.out.println("  /\\");
        System.out.println(" /  \\");
        System.out.println("/____\\");
    }
}

public class ShapeFactory {
    /**
     * @param shapeType a string
     * @return Get object of type Shape
     */
    public Shape getShape(String shapeType) {
        // Write your code here
        if(shapeType.equals("Square")){
            return new Square();
        }else if(shapeType.equals("Triangle")){
            return new Triangle();
        }else if(shapeType.equals("Rectangle")){
            return new Rectangle();
        }else{
            return null;
        }
    }
}

results matching ""

    No results matching ""