博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
[LintCode] Shape Factory
阅读量:6303 次
发布时间:2019-06-22

本文共 1982 字,大约阅读时间需要 6 分钟。

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;    }}

转载地址:http://nzbxa.baihongyu.com/

你可能感兴趣的文章
【爬虫】在Xpath中使用正则
查看>>
3D分子构型该怎么优化
查看>>
Python list 数据类型:列表
查看>>
7)查找[2]二叉排序树以及查找
查看>>
less学习笔记
查看>>
在github上写博客
查看>>
Friendly Filmic Tonemapping
查看>>
我的友情链接
查看>>
cisco路由器的DNS配置
查看>>
产品经理在没有人带的情况下如何自我学习?
查看>>
我的友情链接
查看>>
LNMP源码编译安装之PHP-5.5.32
查看>>
软考网络工程师5天修炼读书笔记
查看>>
我的友情链接
查看>>
Nginx之动静分离
查看>>
Path 路径类 | Directory 文件夹类 | File 文件类 | FileStream 文件流类
查看>>
CentOS6.5安装jdk1.8
查看>>
阿里钉钉软件送100元啦,可支付宝提现
查看>>
Perl 连接Oracle 数据库_libydwei2007-ChinaUnix博客
查看>>
我的友情链接
查看>>