工厂模式
工厂模式提供了一种创建对象的方式。它将创建的过程隐藏了起来,调用者只负责获取,不关心创建的细节。
// 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,构造的圆半径是多少,构造的矩形长宽是多少并不关心。此时就可以使用工厂模式。
该类和建造者类有一定的相似,具体我会在建造者类里说明。