• [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;
        }
    };
  • 相关阅读:
    EditPlus保存文件时不生成其备份文件的方法
    一台电脑同时运行多个tomcat配置方法
    Dom4j写XML
    .....
    编程备忘录
    背包问题
    chrome新版不再支持-webkit-text-size-adjust
    安装grunt需要的grunt插件
    初学web前端
    心情烦躁、、
  • 原文地址:https://www.cnblogs.com/grandyang/p/5512133.html
Copyright © 2020-2023  润新知