LintCode 497. Shape Factory (工厂模式)

本文介绍了一个简单的工厂模式应用实例——形状工厂。通过该工厂可以创建三种不同的形状:三角形、正方形和矩形,并演示了如何用C++代码实现这些形状的绘制。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

  1. Shape Factory
    中文English
    Factory is a design pattern in common usage. Implement a ShapeFactory that can generate correct shape.

You can assume that we have only three different shapes: Triangle, Square and Rectangle.

Example
Example 1:

Input:
ShapeFactory sf = new ShapeFactory();
Shape shape = sf.getShape(“Square”);
shape.draw();
Output:

| |

Example 2:

Input:
ShapeFactory sf = new ShapeFactory();
shape = sf.getShape(“Triangle”);
shape.draw();
Output:
/
/
/____
Example 3:

Input:
ShapeFactory sf = new ShapeFactory();
shape = sf.getShape(“Rectangle”);
shape.draw();
Output:

解法1:
注意:

  1. \的使用。因为\是转义字符。
    代码如下:
/**
 * 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 {
    void draw() const {
       cout<<" ----"<<endl;
       cout<<"|    |"<<endl;
       cout<<" ----"<<endl;
    }
};

class Square: public Shape {
    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 == "Triangle") {
            return new Triangle();
        } else if (shapeType == "Rectangle") {
            return new Rectangle();
        } else if (shapeType == "Square") {
            return new Square();
        } else {
            return NULL;
        }
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值