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;
        }
    };
  • 相关阅读:
    zabbix5.0安装
    Ubuntu下为服务器添加新用户
    oss存储的安装与使用
    模型结构可视化
    GPU算力查询
    台式机PC挂载共享盘
    Python批量拷贝文件
    NVIDIA显卡驱动,CUDA,CUDNN安装流程
    使用Docker GPU训练环境安装过程中所碰到的问题
    Cannot connect to the Docker daemon at unix:///var/run/docker.sock. Is the docker daemon running?
  • 原文地址:https://www.cnblogs.com/grandyang/p/5512133.html
Copyright © 2011-2022 走看看