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 }

 

转载于:https://www.cnblogs.com/beiyeqingteng/p/5662231.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值