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;
        }
    };
  • 相关阅读:
    Linux development tools
    Windows Live Mail: getting fewer ads
    美国签证(B1)经验总结
    谁要windows live messenger(msn8.0)的邀请?
    Use Google Calendar in Office
    C#中的ReaderWriterLock和LockFree Data Structure
    第一次看到“谷歌”出现在google.cn上
    解决SQL安装时提示挂起的方法
    asp 常见错误 不能打开注册表关键字 的处理方法
    Apache Web服务器安全配置全攻略
  • 原文地址:https://www.cnblogs.com/grandyang/p/5512133.html
Copyright © 2011-2022 走看看