情景:创建不同图形的对象
先创建不同的工厂对象,再由这些工厂对象的生产方法创建生产(返回)对应的图形对象
特点:将图形对象设置参数的过程隐藏(包装)在工厂的生产方法中
//配置文件的形式:
// *.txt
// xml
// json
//
class Figure
{
public:
virtual void display() const =0;
virtual double area()=0;
virtual ~Figure() {}
};
class Circle
: public Figure
{
public:
Circle(double radius)
: _radius(radius)
{}
void display() const
{ cout << "circle"; }
double area()
{
return 3.14159 * _radius * _radius;
}
~Circle() { cout << "~Circle()" << endl; }
private:
double _radius;
};
class Rectangle
: public Figure
{
public:
Rectangle(double length, double width)
: _length(length)
, _width(width)
{}
~Rectangle() { cout << "~Rectangle()" << endl; }
void display() const
{ cout << "rectangle"; }
double area()
{ return _length * _width; }
private:
double _length;
double _width;
};
class Triangle
: public Figure
{
public:
Triangle(double a, double b, double c)
: _a(a)
, _b(b)
, _c(c)
{}
~Triangle() { cout << "~Triangle()" << endl; }
void display() const
{ cout << "triangle";}
double area()
{
double p = (_a + _b + _c) / 2;
return sqrt(p * (p - _a) * (p - _b) * (p - _c));
}
private:
double _a;
double _b;
double _c;
};
void display(Figure * fig)
{
fig->display();
cout << "的面积是:" << fig->area() << endl;
}
1、静态工厂模式
//简单工厂模式(静态工厂方法)
//问题:
// 1. 没有遵循开闭原则
// 2. 没有遵循单一职责原则
class Factory
{
public:
static Figure * create(const string & figName)
{
Figure * fig = nullptr;
if(figName == "rectangle") {
//预处理
fig = new Rectangle(10, 11);
} else if (figName == "circle") {
fig = new Circle(10);
} else if(figName == "triangle") {
fig = new Triangle(3, 4, 5);
}
return fig;
}
static Figure * createRectangle()
{
//读取配置文件 txt xml json
//预处理
Figure * fig = new Rectangle(5, 6);
return fig;
}
static Figure * createCircle()
{
//读取配置文件 txt xml json
//预处理
Figure * fig = new Circle(10);
return fig;
}
static Figure * createTriangle()
{
//输入数据 input, 一般放到配置文件
//
//读取配置文件 txt xml json
//预处理
Figure * fig = new Triangle(3, 4, 5);
return fig;
}
};
int main(void)
{
Figure * rectangle = Factory::createRectangle();
Figure * circle = Factory::createCircle();
Figure * triangle = Factory::createTriangle();
display(rectangle);
display(circle);
display(triangle);
return 0;
}
//工厂模式
// 1. 遵循开闭原则
// 2. 遵循单一职责原则
//
//应用场景:
// 1. 并不是什么时候都适合使用工厂模式的
// 2. 对于简单对象,直接创建即可
// 3. 工厂模式针对与复杂对象, 批量生产的
class Factory
{
public:
virtual Figure * create() = 0;
virtual ~Factory() {}
};
class RectangleFactory
: public Factory
{
public:
Figure * create()
{
return new Rectangle(10, 11);
}
};
class CircleFactory
: public Factory
{
public:
Figure * create()
{
return new Circle(10);
}
};
void test1()
{
//创建用于生产特定图形的工厂对象
unique_ptr<Factory> rectFact(new RectangleFactory());
//由该工厂对象创造对应的图形
unique_ptr<Figure> rect(rectFact->create());
unique_ptr<Factory> circleFact(new CircleFactory());
unique_ptr<Figure> circle(circleFact->create());
display(rect.get());
display(circle.get());
}
int main()
{
test1();
return 0;
}