(本博客旨在个人总结回顾)
目录
1、详情:
简单工厂模式(静态工厂方法模式)并不属于Gof中的23设计模式之一。
简单工厂模式包含三个角色:
①工厂类角色:这是本模式的核心,含有一定的判断逻辑,根据逻辑不同产生具体的工厂产品。例子中的:MyAlgorithmFactory
②抽象产品类角色:一般为具体产品继承的父类或者实现的接口。例子中的:MyAlgorithm
③具体产品类角色:继承或实现抽象产品类角色,工厂类创建的是此角色的实例。例子中的:MyAdd,MySub,MyMul
2、应用:
简单工厂模式适用于业务较简单的情况,一般用于小项目或者具体产品很少扩展的情况。(扩展产品需要修改工厂类,违反开闭原则)
3、UML类图:
4、代码实现:
MyAlgorithm.h
#pragma once
//算法接口类
class MyAlgorithm
{
public:
MyAlgorithm();
~MyAlgorithm();
public:
virtual double GetResult(double param1, double param2) = 0;
};
MyAlgorithm.cpp
#include "stdafx.h"
#include "MyAlgorithm.h"
MyAlgorithm::MyAlgorithm()
{
}
MyAlgorithm::~MyAlgorithm()
{
}
MyAdd.h
#pragma once
#include "MyAlgorithm.h"
class MyAdd:public MyAlgorithm
{
public:
MyAdd();
~MyAdd();
public:
double GetResult(double param1, double param2);
};
MyAdd.cpp
#include "stdafx.h"
#include "MyAdd.h"
MyAdd::MyAdd()
{
}
MyAdd::~MyAdd()
{
}
double MyAdd::GetResult(double param1, double param2)
{
return param1 + param2;
}
MySub.h
#pragma once
#include "MyAlgorithm.h"
class MySub:public MyAlgorithm
{
public:
MySub();
~MySub();
public:
double GetResult(double param1, double param2);
};
MySub.cpp
#include "stdafx.h"
#include "MySub.h"
MySub::MySub()
{
}
MySub::~MySub()
{
}
double MySub::GetResult(double param1, double param2)
{
return param1 - param2;
}
MyMul.h
#pragma once
#include "MyAlgorithm.h"
class MyMul:public MyAlgorithm
{
public:
MyMul();
~MyMul();
public:
double GetResult(double param1, double param2);
};
MyMul.cpp
#include "stdafx.h"
#include "MyMul.h"
MyMul::MyMul()
{
}
MyMul::~MyMul()
{
}
double MyMul::GetResult(double param1, double param2)
{
return param1 * param2;
}
MyAlgorithmFactory.h
#pragma once
#include "MyAlgorithm.h"
#include "MyAdd.h"
#include "MySub.h"
#include "MyMul.h"
class MyAlgorithmFactory
{
public:
MyAlgorithmFactory();
~MyAlgorithmFactory();
public:
static MyAlgorithm* GetAlgorithm(char cType);
};
MyAlgorithmFactory.cpp
#include "stdafx.h"
#include "MyAlgorithmFactory.h"
MyAlgorithmFactory::MyAlgorithmFactory()
{
}
MyAlgorithmFactory::~MyAlgorithmFactory()
{
}
MyAlgorithm* MyAlgorithmFactory::GetAlgorithm(char cType)
{
switch (cType)
{
case '+':
return new MyAdd();
break;
case '-':
return new MySub();
break;
case '*':
return new MyMul();
break;
default:
break;
}
}
调用代码:
// FactoryMethodMemo.cpp : 定义控制台应用程序的入口点。
//
#include "stdafx.h"
#include "MyAlgorithm.h"
#include "MyAlgorithmFactory.h"
#include <iostream>
using namespace std;
int _tmain(int argc, _TCHAR* argv[])
{
MyAlgorithm* pAlgorithmm = NULL;
pAlgorithmm = MyAlgorithmFactory::GetAlgorithm('+');
cout << "add:" << pAlgorithmm->GetResult(3.0, 5.0) << endl;
delete pAlgorithmm;
pAlgorithmm = NULL;
pAlgorithmm = MyAlgorithmFactory::GetAlgorithm('-');
cout << "sub:" << pAlgorithmm->GetResult(3.0, 5.0) << endl;
delete pAlgorithmm;
pAlgorithmm = NULL;
pAlgorithmm = MyAlgorithmFactory::GetAlgorithm('*');
cout << "mul:" << pAlgorithmm->GetResult(3.0, 5.0) << endl;
delete pAlgorithmm;
pAlgorithmm = NULL;
system("pause");
return 0;
}
输出结果: