Shape Factory

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: TriangleSquare 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();
>>  ----
>> |    |
>>  ----

 1 /**
 2  * Your object will be instantiated and called as such:
 3  * ShapeFactory sf = new ShapeFactory();
 4  * Shape shape = sf.getShape(shapeType);
 5  * shape.draw();
 6  */
 7 interface Shape {
 8     void draw();
 9 }
10 
11 class Rectangle implements Shape {
12     public void draw() {
13         System.out.println(" ----"); 
14         System.out.println("|    |");
15         System.out.println(" ----");    
16     }
17 }
18 
19 class Square implements Shape {
20     public void draw() {
21         System.out.println(" ----"); 
22         System.out.println("|    |");
23         System.out.println("|    |");
24         System.out.println(" ----");
25     }
26 }
27 
28 class Triangle implements Shape {
29     public void draw() {
30         System.out.println("  /\\"); 
31         System.out.println(" /  \\");
32         System.out.println("/____\\");
33     }
34 }
35 
36 public class ShapeFactory {
37     /**
38      * @param shapeType a string
39      * @return Get object of type Shape
40      */
41     public Shape getShape(String shapeType) {
42         if (shapeType.toLowerCase().equals("square")) {
43             return new Square();
44         } else if (shapeType.toLowerCase().equals("triangle")) {
45             return new Triangle();
46         } else if (shapeType.toLowerCase().equals("rectangle")) {
47             return new Rectangle();
48         } else {
49             return null;
50         }
51     }
52 }

 

posted @ 2016-07-12 06:37  北叶青藤  阅读(502)  评论(0编辑  收藏  举报