C language and design mode (single-piece Mode)

Source: Internet
Author: User

[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;}

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.