1.单例设计模式(singleton)
整个进程,仅能创建一个类变量
class A
{
private:
A() {} //析构函数私有化
static A *m_pA; //单例记录变量
class Adispoes //m_pA 自动释放变量
{
public:
~Adispoes() //析构函数自动释放
{
if (A::m_pA) //单例已创建
{
delete A::m_pA;
A::m_pA = NULL;
}
}
};
public:
static A *getA() //获取单例指针
{
if (m_pA == NULL)
{
m_pA = new A();
static Adispoes _a; //静态类 主进程结束 自动释放内存
}
return m_pA;
}
};
A* A::m_pA = NULL; //静态变量赋值
2.简单工厂 (SempleFactory)
将类接口封装,将调用者安排的明明白白!
实现
//Api.h
#ifndef __API_HPP__
#define __API_HPP__
#include <stdio.h>
#include <string>
//公开接口的类
class Api
{
public:
virtual void test(std::string str) = 0;
};
//实现逻辑的类 one 不公开接口
class ImplOne : public Api
{
public:
void test(std::string str)
{
printf("this is ImplOne,str %s\n", str.c_str());
}
};
//实现逻辑的类 two 不公开接口
class ImplTwo : public Api
{
public:
void test(std::string str)
{
printf("this is ImplTwo,str %s\n", str.c_str());
}
};
#endif
//SempleFactory.h
#ifndef __SEMPLE_FACTORY_HPP__
#define __SEMPLE_FACTORY_HPP__
/*
简单工厂 Semple Factory
对类进行封装,把调用者安排的明明白白!
此项目,安排调用者调用 ImplOne 或 ImplTwo 任意一个类
*/
#include "Api.h"
#include <map>
typedef void* (*Constructor)(); //防函数 用来记录 类创建函数
//用来记录 类创建函数
class CObjectFactory
{
public:
static void registerClass(std::string className, Constructor constructor)
{
//通过函数名,注册函数
constructors()[className] = constructor;
}
static void* createClass(std::string className)
{
Constructor _constructor = nullptr;
//查询 是否存在当前函数
if (constructors().find(className) != constructors().end())
_constructor = constructors().find(className)->second;
if (nullptr == _constructor)return nullptr;
//返回 类创建函数
return _constructor();
}
private:
inline static std::map<std::string, Constructor>& constructors()
{
//创建一个静态 红黑树,记录 类创建函数
static std::map<std::string, Constructor> _instance;
return _instance;
}
};
//工厂类
class Factory
{
public:
static Api* createApi()
{
Api* _api = nullptr;
//获取创建函数
//可根据需求 通过配置 或 其他防止改变 创建函数
_api = static_cast<Api*>(CObjectFactory::createClass("ImplOne"));
//_api = static_cast<Api*>(CObjectFactory::createClass("ImplTwo"));
return _api;
}
};
//宏原型
//class ImplOneHelper
//{
//public:
// ImplOneHelper()
// {
// //注册创建函数
// CObjectFactory::registerClass("ImplOne", ImplOneHelper::createrObjectFunc);
// }
//
// //创建函数
// static void* createrObjectFunc()
// {
// return new ImplOne;
// }
//};
//注册指定 类的 创建函数
#define REG_CLASS(class_name) \
class class_name##Helper\
{\
public:\
class_name##Helper()\
{\
CObjectFactory::registerClass(#class_name, class_name##Helper::createrObjectFunc);\
}\
static void* createrObjectFunc()\
{\
return new class_name##;\
}\
};\
class_name##Helper class_name##helper;
#endif
调用方式
//main.cpp
#include "SempleFactory.h"
//注册 创建函数
REG_CLASS(ImplOne);
REG_CLASS(ImplTwo);
int main()
{
Api* _api = Factory::createApi();
_api->test("Fectory");
return 0;
}