文章目录
c++常用设计模式
在工厂模式中,我们在创建对象时不会对客户端暴露创建逻辑,并且是通过使用一个共同的接口来指向新创建的对象。工厂模式作为一种创建模式,一般在创建复杂对象时,考虑使用;在创建简单对象时,建议直接new完成一个实例对象的创建。
1,工程目录
2,测试效果
3,auto_factory.h — 自动注册工厂代码
#pragma once
#include <functional>
#include <map>
#include <memory>
#include <string>
namespace oly {
/**
* T 需要传入基类
*/
template <typename T>
class auto_factory {
public:
/**
* N 子类,这里会把对应子类添加到Map中
*/
template <typename N>
struct register_t {
template <typename... Args>
register_t(const std::string& key, Args... args)
{
auto_factory::instance()->_map.emplace(key, [=] { return new N(args...); });
}
};
/**
* 普通指针
*/
static auto normal_ptr(const std::string& key) -> T*
{
return auto_factory::instance()->find(key);
}
/**
* unique_ptr指针
*/
static std::unique_ptr<T> unique_ptr(const std::string& key)
{
return std::unique_ptr<T>(normal_ptr(key));
}
/**
* shared_ptr指针
*/
static std::shared_ptr<T> shared_ptr(const std::string& key)
{
return std::shared_ptr<T>(normal_ptr(key));
}
private:
auto_factory(){};
auto_factory(const auto_factory&) = delete;
auto_factory(auto_factory&&) = delete;
auto_factory& operator=(const auto_factory&) = delete;
/**
* 单例模式
*/
static auto instance() -> auto_factory<T>*
{
static auto_factory<T> ins;
return &ins;
}
auto find(const std::string& key) -> T*
{
if (_map.find(key) == _map.end())
throw std::invalid_argument("key is not exist!");
return _map[key]();
}
std::map<std::string, std::function<T*()>> _map;
};
} // namespace oly
4,base_message.h — 注册类基类,及工厂代码接口
#include <iostream>
#include "auto_factory.h"
class BaseMessage {
public:
virtual void display() = 0;
};
/**
* 注册基类
*/
#define AF_OBJECT oly::auto_factory<BaseMessage>
/**
* 注册子类,这里没有对继承关系进行判断,需要保证继承关系
*/
#define REGISTER_MESSAGE_VNAME(T) reg_msg_##T##_
//注意,此处写法有问题,后面有详细说明
#define REGISTER_AF_OBJECT_CLASS(T, ...) AF_OBJECT::register_t<T> REGISTER_MESSAGE_VNAME(T)(#T, ##__VA_ARGS__)
#define QUERY_AF_OBJECT_BY_CLASS(T) AF_OBJECT::normal_ptr (#T)
#define QUERY_AF_OBJECT_BY_KEY(key) AF_OBJECT::normal_ptr (key)
5,message.h — 要注册的N个类
#include "base_message.h"
class FirstB : public BaseMessage {
public:
void display() override
{
std::cout << __func__ << " FirstB\n";
}
};
REGISTER_AF_OBJECT_CLASS(FirstB);
class SecondB : public BaseMessage {
public:
SecondB(const std::string name = "")
{
nameString = name;
}
void display() override
{
std::cout << __func__ << " SecondB\n";
std::cout << nameString << "\n";
}
private:
std::string nameString;
};
REGISTER_AF_OBJECT_CLASS(SecondB, "Welcome"); //带参构造函数
class ThirdB : public BaseMessage {
public:
ThirdB(int age, const std::string name = "")
{
nameString = name;
ageInt = age;
}
void display() override
{
std::cout << __func__ << " ThirdB\n";
std::cout << nameString << ":" << ageInt << "\n";
}
private:
std::string nameString;
int ageInt;
};
REGISTER_AF_OBJECT_CLASS(ThirdB, 20, "Tom"); //带参构造函数
6,main.cpp
#include "message.h"
int main()
{
std::string class_name = "FirstB";
REGISTER_AF_OBJECT_CLASS(FirstB);
REGISTER_AF_OBJECT_CLASS(SecondB, "Welcome"); //带参构造函数
REGISTER_AF_OBJECT_CLASS(ThirdB, 20, "Tom"); //带参构造函数
QUERY_AF_OBJECT_BY_KEY(class_name)->display();
QUERY_AF_OBJECT_BY_CLASS(SecondB)->display();
QUERY_AF_OBJECT_BY_KEY("SecondB")->display();
QUERY_AF_OBJECT_BY_KEY("ThirdB")->display();
return 0;
}
7,Makefile
CXX=g++
LDFLAGS=-std=c++11 -O1 -g -w -fopenmp
TARGET=main.app
INCLUDE_BASE = ./
INCLUDE_DIR = -I"$(INCLUDE_BASE)"
SRC_BASE = ./
SRCS := $(wildcard $(SRC_BASE)/*.cpp)
OBJS := $(SRCS:%.cpp=%.o)
# 编译工程,生成可执行文件
all:$(OBJS)
@echo "Compilling......"
$(CXX) $(LDFLAGS) -o $(TARGET) $^ $(CFLAGS) $(LIBS)
%.o:%.cpp
$(CXX) $(LDFLAGS) -c $< -o $@ $(LIBS) $(CFLAGS) $(INCLUDE_DIR)
@echo " "
.PHONY:clean
clean:
rm -rf $(TARGET) $(OBJS) *.gch
8,报错:multiple definition of `reg_msg_MockModule_’
8.1,解决:static
修改为以下代码
base_message.h — 注册类基类,及工厂代码接口
#include <iostream>
#include "auto_factory.h"
class BaseMessage {
public:
virtual void display() = 0;
};
/**
* 注册基类
*/
#define AF_OBJECT oly::auto_factory<BaseMessage>
/**
* 注册子类,这里没有对继承关系进行判断,需要保证继承关系
*/
#define REGISTER_MESSAGE_VNAME(T) reg_msg_##T##_
#define REGISTER_AF_OBJECT_CLASS(T, ...) static AF_OBJECT::register_t<T> REGISTER_MESSAGE_VNAME(T)(#T, ##__VA_ARGS__)
#define QUERY_AF_OBJECT_BY_CLASS(T) AF_OBJECT::normal_ptr (#T)
#define QUERY_AF_OBJECT_BY_KEY(key) AF_OBJECT::normal_ptr (key)