形状工厂-lintcode

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<<" ----"<

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()
        


你可能感兴趣的:(算法,LintCode,设计模式)