码迷,mamicode.com
首页 > 其他好文 > 详细

Shape Factory

时间:2016-07-12 07:52:17      阅读:157      评论:0      收藏:0      [点我收藏+]

标签:

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 }

 

Shape Factory

标签:

原文地址:http://www.cnblogs.com/beiyeqingteng/p/5662231.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!