工廠模式
工廠模式提供了一種創建對象的方式。它將創建的過程隱藏了起來,調用者只負責獲取,不關心創建的細節。
// Shape.h
#pragma once
// 抽象類
class BaseShape
{
public:
BaseShape(int x, int y) : x_(x), y_(y);
void draw() = 0;
private:
int x_, y_;
}
//ShapeImpl.h
#pragma once
#include "Shape.h"
#include <iostream>
class Circle final : public BaseShape
{
public:
Circle(int x, int y, int r) : BaseShape(x, y), r_(r) {};
virtual void draw() override
{
std::cout << "This is a circle" << std::endl;
}
private:
int r_;
}
class Square final : public BaseShape
{
public:
Square(int x, int y, int l) : BaseShape(x, y), l_(l) {};
virtual void draw() override
{
std::cout << "This is a square" << std::endl;
}
private:
int l_;
}
class Rectangle final : public BaseShape
{
public:
Rectangle (int x, int y, int l, int w) : BaseShape(x, y), l_(l), w_(w) {};
virtual void draw() override
{
std::cout << "This is a rectangle " << std::endl;
}
private:
int l_, w_;
}
// ShapeFactory.h
#pragma once
#include "Shape.h"
enum class ShapeType
{
CIRCLE,
SQUARE,
RECTANGLE
}
//工廠類
class ShapeFactory
{
public:
BaseShape* getShape(ShapeType t, int x, int y);
}
// ShapeFactory.cpp
#include "ShapeFactory.h"
#include "ShapeImpl.h"
BaseShape* ShapeFactory::getShape(ShapeType t, int x, int y)
{
switch(t)
{
case ShapeType::CIRCLE:
{
return new Circle(x, y, 1);
}
case ShapeType::SQUARE:
{
return new Square(x, y, 1);
}
case ShapeType::RECTANGLE:
{
return new Rectanngle(x, y, 2, 3);
}
default:
{
return nullptr;
}
}
//main.cpp
#include "ShapeFactory.h"
int main(void)
{
ShapeFactory f;
BaseShape* ptr = f.getShape(ShapeType::CIRCLE, 0, 0);
ptr->draw();
delete ptr;
// print: This is a circle
ptr = f.getShape(ShapeType::SQUARE, 0, 0);
ptr->draw();
delete ptr;
// print: This is a square
Shape* ptr = f.getShape(ShapeType::RECTANGLE, 0, 0);
ptr->draw();
delete ptr;
// print: This is a rectangle
return 0;
}
可以看到,當外界調用時,它只看到了兩個類:BaseShape和ShapeFactory。對於ShapeFactory如何構造BaseShape,構造的圓半徑是多少,構造的矩形長寬是多少並不關心。此時就可以使用工廠模式。
該類和建造者類有一定的相似,具體我會在建造者類裏說明。