zoukankan      html  css  js  c++  java
  • [LintCode] 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: Triangle, Square 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();

    这道题让我们求形状工厂,实际上就是Factory pattern的一个典型应用,说得是有一个基类Shape,然后派生出矩形,正方形,和三角形类,每个派生类都有一个draw,重写基类中的draw,然后分别画出派生类中的各自的形状,然后在格式工厂类中提供一个派生类的字符串,然后可以新建对应的派生类的实例,没啥难度,就是考察基本的知识。

    class Shape {
    public:
        virtual void draw() const=0;
    };
    
    class Rectangle: public Shape {
    public:
        void draw() const {
            cout << " ---- " << endl;
            cout << "|    |" << endl;
            cout << " ---- " << endl;
        }
    };
    
    class Square: public Shape {
    public:
        void draw() const {
            cout << " ---- " << endl;
            cout << "|    |" << endl;
            cout << "|    |" << endl;
            cout << " ---- " << endl;
        }
    };
    
    class Triangle: public Shape {
    public:
        void draw() const {
            cout << "  /\ " << endl;
            cout << " /  \ " << endl;
            cout << "/____\ " << endl;
        }
    };
    
    class ShapeFactory {
    public:
        /**
         * @param shapeType a string
         * @return Get object of type Shape
         */
        Shape* getShape(string& shapeType) {
            if (shapeType == "Square") return new Square();
            else if (shapeType == "Triangle") return new Triangle();
            else if (shapeType == "Rectangle") return new Rectangle();
            else return NULL;
        }
    };
  • 相关阅读:
    JSON.NET C# 类库
    javascript绑定事件,JQuery绑定事件
    C#批量上传图片
    关闭或重启Windows Server 操作系统时,系统会弹出一个提示窗口
    Asp.net组织结构图控件,思维导图控件
    C# 判断是否可以连接服务器?
    javascript获取select,checkbox,radio的值
    IE、FF、Safari、OP不同浏览器兼容报告
    Microsoft Windows Server 2008 Standard Edition激活码申请方法
    自动修改电脑IP地址.bat
  • 原文地址:https://www.cnblogs.com/grandyang/p/5512133.html
Copyright © 2011-2022 走看看