形状工厂-lintcode

来源:互联网 发布:腾讯微云网盘for mac 编辑:程序博客网 时间:2024/05/02 00:33

C++代码:

/** * Your object will be instantiated and called as such: * ShapeFactory* sf = new ShapeFactory(); * Shape* shape = sf->getShape(shapeType); * shape->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 {    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();        }    }};

python代码:

"""Your object will be instantiated and called as such:sf = ShapeFactory()shape = sf.getShape(shapeType)shape.draw()"""class Shape:    def draw(self):        raise NotImplementedError('This method should have implemented.')class Triangle(Shape):    def draw(self):        print '  /\\  '        print ' /  \\ '        print '/____\\'class Rectangle(Shape):    def draw(self):        print ' ---- '        print r'|    |'        print r' ---- 'class Square(Shape):    def draw(self):        print ' ---- '        print '|    |'        print '|    |'        print ' ---- 'class ShapeFactory:    # @param {string} shapeType a string    # @return {Shape} Get object of type Shape    def getShape(self, shapeType):        if shapeType == 'Triangle':            return Triangle()        if shapeType == 'Rectangle':            return Rectangle()        if shapeType == 'Square':            return Square()        


0 0
原创粉丝点击