形状工厂-lintcode

39 篇文章 0 订阅
2 篇文章 0 订阅

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


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值