引子

接下来以造墙为例,探讨一下工厂方法模式。

首先,我们先定义一个墙。墙应该有:

  • 底部起止二维坐标。
  • 墙的海拔(相对于某个基线的高度或z坐标)。
  • 墙的高度。

代码如下:

class Wall
{
protected:
    Wall(Point2D start, Point2D end, int elevation, int height)
        : start(start), end(end), elevation(elevation), height(height) {}

private:
    Point2D start, end;
    int elevation, height;
};

接下来,为了让墙更接近实际,引入材质和厚度,创建新的墙类SolidWall

enum class Material
{
    brick, concrete
};

class SolidWall : public Wall
{
protected:
    SolidWall(Point2D start, Point2D end, int elevation, int height,
              int width, Material material)
        : Wall(start, end, elevation, height), width(width), material(material) {}
public:
    static SolidWall create_brick(Point2D start, Point2D end, int elevation, int height)
    {
        return {start, end, elevation, height, 120, Material::brick};
    }
    
    static unique_ptr<SolidWall> create_concrete(Point2D start, Point2D end, int elevation, int height)
    {
        return make_unique<SolidWall>(start, end, elevation, height, 375, Material::concrete);
    }
    
private:
    int width;
    Material material;
};

我们添加了两个静态方法,用于创建两种墙,可自己决定返回什么对象。这两种静态方法都被称为 工厂方法,它们强制用户创建指定类型而非任意类型的墙。

我们现在可以造两种墙了,但还无法判断墙与墙之间的相交。我们需要跟踪记录创建好的每一堵墙才能解决这个问题,但显然在SolidWall类里是无法完成这个任务的。该怎么办呢,请看 工厂方法模式

阅读全文 »
0%