加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

[LintCode] Shape Factory

发布时间:2020-12-14 02:15:08 所属栏目:百科 来源:网络整理
导读:Problem Factory is design pattern in common usage. Implement a ShapeFactory that can generate correct shape. Example ShapeFactory sf = new ShapeFactory();Shape shape = sf.getShape("Square");shape.draw(); ----| || | ----shape = sf.getShape(

Problem

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

Example

ShapeFactory sf = new ShapeFactory();
Shape shape = sf.getShape("Square");
shape.draw();
 ----
|    |
|    |
 ----

shape = sf.getShape("Triangle");
shape.draw();
   /
  /  
 /____

shape = sf.getShape("Rectangle");
shape.draw();
  ----
 |    |
  ----

Note

这道题考了interface & implementation & override,具体概念如下:

Interface: A Java interface is a bit like a class,except that it can only contain method signatures and fields,which is saying that it cannot contain any implementation of the methods. You can use interface to achieve polymorphism.

Implementation: To declare a class that implements an interface,you have to include an implements clause in the class definition. Your class can implement more than one interface.

Overriding: If subclass provides the specific/close implementation of the method that has been provided by one of its parent class,it is known as method overriding.

除此之外,还需要注意正则表达式的写法。

Solution

interface Shape {
    void draw();
}

class Rectangle implements Shape {
    @Override
    public void draw() {
        System.out.println(" ----"); 
        System.out.println("|    |");
        System.out.println(" ----");    
    }
}

class Square implements Shape {
    @Override
    public void draw() {
        System.out.println(" ----"); 
        System.out.println("|    |");
        System.out.println("|    |");
        System.out.println(" ----");
    }
}

class Triangle implements Shape {
    @Override
    public void draw() {
        System.out.println("  /"); 
        System.out.println(" /  ");
        System.out.println("/____");
    }
}

public class ShapeFactory {
    public Shape getShape(String shapeType) {
        if (shapeType.equalsIgnoreCase("Rectangle")) return new Rectangle();
        else if (shapeType.equalsIgnoreCase("Square")) return new Square();
        else if (shapeType.equalsIgnoreCase("Triangle")) return new Triangle();
        return null;
    }
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读