使用模板实现、替代工厂模式:
/* ---示例代码----*/
#include <memory>
#include <iostream>
class ShapeFT
{
public:
virtual void draw() = 0;
protected:
ShapeFT(){};
~ShapeFT(){ std::cout << "~Shape\n"; };
};
class RectangleFT
:public ShapeFT
{
public:
void draw(){ std::cout << "Rectangle draw;\n"; }
RectangleFT(){}
~RectangleFT(){ std::cout << "~RectangleFT\n"; }
};
class CirleFT
:public ShapeFT
{
public:
void draw(){ std::cout << "Ciecle draw\n"; }
CirleFT(){}
~CirleFT(){ std::cout << "~Cirle draw\n"; }
};
template<typename T>
class FactoryFT
{
public:
static std::shared_ptr<T> Creator( void )
{
return std::make_shared<T>();
}
};
#pragma once
/* ---示例代码----*/
工厂模式+反射实现抽象工厂模式:
/* ---示例代码----*/
/*通过简单工厂+反射的形式才改进抽象工厂模式,可以减少类的数量,易于扩展。*/
#include <iostream>
#include <map>
#include <string>
//函数指针类型,指向类实例的回调函数。
typedef void* ( *PTRCreateObject )( void );
//工厂类
class Factory_2
{
private:
std::map<std::string, PTRCreateObject> m_classMap;
Factory_2(){}
public:
void* getClassByName( std::string className );//通过类名获取对应对象。
void registClass( std::string name, PTRCreateObject method );//保存对象到map中
static Factory_2& getInstance();//获取单个工厂类的实例对象
};
//注册动作类
class RegisterAction
{
public:
RegisterAction( std::string className, PTRCreateObject ptrCreateFn ){
Factory_2::getInstance().registClass( className, ptrCreateFn );
}
};
//注册操作的宏;REGISTER(className)
//回调函数:objectCreator##className();
//注册对象:g_creatorRegister##classsName
#define REGISTER(className) \
className* objectCreator##className(){ \
return new className; \
} \
RegisterAction g_creatorRegister##className( \
#className,(PTRCreateObject)objectCreator##className)
class AbstractProduct_A
{
public:
AbstractProduct_A() {}
virtual ~AbstractProduct_A(){};
};
// 派生类ConcreateProductA,继承自AbstractProductA,代表产品A的第一种实现
class ConcreateProduct_A1
: public AbstractProduct_A
{
public:
ConcreateProduct_A1(){
std::cout << "a1\n";
}
virtual ~ConcreateProduct_A1(){
std::cout << "~a1\n";
}
};
//注册。不能在头文件中注册。转移到main函数前注册。全局注册。
//REGISTER( ConcreateProduct_A1 );
// 派生类ConcreateProductA2,继承自AbstractProductA,代表产品A的第二种实现
class ConcreateProduct_A2
: public AbstractProduct_A
{
public:
ConcreateProduct_A2(){ std::cout << "a2\n;"; }
virtual ~ConcreateProduct_A2(){ std::cout << "~a2\n"; }
};
//注册A2产品
//REGISTER( ConcreateProduct_A2 );
// 抽象基类AbstractProduct_B,代表产品B的抽象
class AbstractProduct_B
{
public:
AbstractProduct_B() {}
virtual ~AbstractProduct_B(){};
};
// 派生类ConcreateProductB1,继承自AbstractProduct_B,代表产品B的第一种实现
class ConcreateProduct_B1
: public AbstractProduct_B
{
public:
ConcreateProduct_B1(){ std::cout << "b1\n:"; }
virtual ~ConcreateProduct_B1(){
std::cout << "~b1\n";
}
};
//注册B1
//REGISTER( ConcreateProduct_B1 );
// 派生类ConcreateProductB2,继承自AbstractProduct_B,代表产品B的第二种实现
class ConcreateProduct_B2
: public AbstractProduct_B
{
public:
ConcreateProduct_B2(){
std::cout << "b2\n";
}
virtual ~ConcreateProduct_B2(){
std::cout << "~b2\n";
}
};
//注册B2
//REGISTER( ConcreateProduct_B2 );
#pragma once
/* ---示例代码----*/