[Disclaimer: All Rights Reserved. You are welcome to reprint it. Do not use it for commercial purposes. Contact Email: feixiaoxing @ 163.com]
Anyone who has experience in the interview, or who is familiar with the design model, will be familiar with the single-piece mode. For many interviewers, the single-piece mode is also a retained project for their interviews. In fact, I think the single-piece mode is not a design mode. It can be a skill at most.
The single-piece mode is generally written in C ++.
#include <string.h>#include <assert.h>class object{public: static class object* pObject; static object* create_new_object() { if(NULL != pObject)return pObject;pObject = new object();assert(NULL != pObject);return pObject; }private: object() {} ~object() {}};class object* object::pObject = NULL;
The trick of the single-piece mode is that the class constructor is a private function. But must the class constructor be created? What should we do? Then only static functions are used. We can see that the constructor called in static is so simple.
int main(int argc, char* argv[]){object* pGlobal = object::create_new_object();return 1;}
The above describes how to write c ++. How to Write c language? It is also simple. You can also give it a try.
typedef struct _DATA{ void* pData;}DATA;void* get_data(){ static DATA* pData = NULL; if(NULL != pData) return pData; pData = (DATA*)malloc(sizeof(DATA)); assert(NULL != pData); return (void*)pData;}