KBengine中的设计模式

KBengine那么大的代码量,读起来真的心累,不过认真读总能发现一些有趣的东西,比如设计模式。

1.单例模式:

template <typename T> 
class Singleton
{
protected:
	static T* singleton_;

public:
	Singleton(void)
	{
		assert(!singleton_);
#if defined(_MSC_VER) && _MSC_VER < 1200	 
		int offset = (int)(T*)1 - (int)(Singleton <T>*)(T*)1;
		singleton_ = (T*)((int)this + offset);
#else
		singleton_ = static_cast< T* >(this);
#endif
	}
	
	
	~Singleton(void){  assert(singleton_);  singleton_ = 0; }
	
	static T& getSingleton(void) { assert(singleton_);  return (*singleton_); }
	static T* getSingletonPtr(void){ return singleton_; }
};

#define KBE_SINGLETON_INIT( TYPE )							\
template <>	 TYPE * Singleton< TYPE >::singleton_ = 0;	\
	
}

2.简单工厂模式

class DataDownloads;

class DataDownload : public thread::TPTask
{
public:
	DataDownload(PyObjectPtr objptr, 
		const std::string & descr, int16 id);

	virtual ~DataDownload();
	
	virtual bool checkDescr(){ return true; }

	void pDataDownloads(DataDownloads* pDataDownloads){ pDataDownloads_ = pDataDownloads; }
	DataDownloads* pDataDownloads(){ return pDataDownloads_; }

	virtual thread::TPTask::TPTaskState presentMainThread();

	void entityID(ENTITY_ID entityID){ entityID_ = entityID; }
	ENTITY_ID entityID(){ return entityID_; }

	bool send(const Network::MessageHandler& msgHandler, Network::Bundle* pBundle);

	void id(int16 i){ id_ = i; }
	int16 id() const{ return id_; }

	uint32 totalBytes() const{ return totalBytes_; }

	virtual char* getOutStream(){ return stream_; }

	virtual int8 type() = 0;
protected:
	PyObjectPtr objptr_;
	std::string descr_;
	int16 id_;
	DataDownloads* pDataDownloads_;

	bool sentStart_;

	uint32 totalBytes_;

	// 总共发送的字节数
	uint32 totalSentBytes_;
	uint32 remainSent_;
	uint32 currSent_;

	char* stream_;

	ENTITY_ID entityID_;

	bool error_;
};

class StringDataDownload : public DataDownload
{
public:
	StringDataDownload(PyObjectPtr objptr, 
		const std::string & descr, int16 id);

	virtual ~StringDataDownload();

	virtual bool process();

	virtual char* getOutStream();

	virtual int8 type();
};

class FileDataDownload : public DataDownload
{
public:
	FileDataDownload(PyObjectPtr objptr, 
		const std::string & descr, int16 id);

	virtual ~FileDataDownload();

	virtual bool process();

	virtual int8 type();
protected:
	std::string path_;
	
};

class DataDownload;


class DataDownloads
{
public:
	DataDownloads();
	~DataDownloads();
	
	int16 pushDownload(DataDownload* pdl);

	void onDownloadCompleted(DataDownload* pdl);

	int16 freeID(int16 id);
private:
	std::map<int16, DataDownload*> downloads_;

	std::set< uint16 > usedIDs_;
};

class DataDownloadFactory
{
public:
	enum DataDownloadType
	{
		DATA_DOWNLOAD_STREAM_FILE = 1,
		DATA_DOWNLOAD_STREAM_STRING = 2
	};

	static DataDownload * create(DataDownloadType dltype, PyObjectPtr objptr, 
			const std::string & desc, int16 id);

};
posted @ 2018-03-20 10:30  丁彬  阅读(281)  评论(0编辑  收藏  举报