如何在程序中加载各个模块(也谈C++多态的威力)

        在一个大型项目或工程中, 经常包含很多模块。 通常而言, 当系统开启的时候, 需要加载各个模块, 下面我们提供一种方法, 顺便看看C++中多态的威力:

#include <iostream>
using namespace std;

// 基础模块
class BASIC_MOD
{
public:
	virtual void start() // 虚函数。 如果没有virtual, 那么则不能正确加载各个模块
	{
		cout << "BASIC_MOD" << endl;
	}
};


// 模块1, 继承基础模块
class MOD1 : public BASIC_MOD
{
public:
	static MOD1 *getInstance()
	{
		static MOD1* pInstance = NULL;
		if(NULL == pInstance)
		{
			pInstance = new MOD1; // 单例
		}

		return pInstance;
	}

	// 模块1启动
	void start()
	{
		cout << "MOD1 is starting..." << endl;
	}
};

class MOD2 : public BASIC_MOD
{
public:
	static MOD2 *getInstance()
	{
		static MOD2* pInstance = NULL;
		if(NULL == pInstance)
		{
			pInstance = new MOD2;
		}

		return pInstance;
	}

	void start()
	{
		cout << "MOD2 is starting..." << endl;
	}
};

class MOD3 : public BASIC_MOD
{
public:
	static MOD3 *getInstance()
	{
		static MOD3* pInstance = NULL;
		if(NULL == pInstance)
		{
			pInstance = new MOD3;
		}

		return pInstance;
	}

	void start()
	{
		cout << "MOD3 is starting..." << endl;
	}
};

class MOD4 : public BASIC_MOD
{
public:
	static MOD4 *getInstance()
	{
		static MOD4* pInstance = NULL;
		if(NULL == pInstance)
		{
			pInstance = new MOD4;
		}

		return pInstance;
	}

	void start()
	{
		cout << "MOD4 is starting..." << endl;
	}
};

class MOD5 : public BASIC_MOD
{
public:
	static MOD5 *getInstance()
	{
		static MOD5* pInstance = NULL;
		if(NULL == pInstance)
		{
			pInstance = new MOD5;
		}

		return pInstance;
	}

	void start()
	{
		cout << "MOD5 is starting..." << endl;
	}
};

class MOD6 : public BASIC_MOD
{
public:
	static MOD6 *getInstance()
	{
		static MOD6* pInstance = NULL;
		if(NULL == pInstance)
		{
			pInstance = new MOD6;
		}

		return pInstance;
	}

	void start()
	{
		cout << "MOD6 is starting..." << endl;
	}
};

BASIC_MOD* mod[] = 
{
	MOD1::getInstance(),
	MOD2::getInstance(),
	MOD3::getInstance(),
	MOD4::getInstance(),
	MOD5::getInstance(),
	MOD6::getInstance(), // 最后这个逗号可要可不要, 但最好加上, 方面其他人增加模块
};


int main()
{
	int size = sizeof(mod) / sizeof(mod[0]);
	int i = 0;
	for(i = 0; i < size; i++)
	{
		mod[i]->start(); // 一种接口, 多种实现, 启动所有模块
	}

	return 0;
}
      结果 大笑

MOD1 is starting...
MOD2 is starting...
MOD3 is starting...
MOD4 is starting...
MOD5 is starting...
MOD6 is starting...


      

你可能感兴趣的:(如何在程序中加载各个模块(也谈C++多态的威力))