C + + Singleton

Source: Internet
Author: User

Design patterns are the focus of programming. Often reviewed during an interview, the Singleton model is the simplest, most common, mostly main mode. So most of the interviews are singleton design patterns for test exams.

Let's take a look at how the singleton pattern is implemented (c + + code):

#include <iostream>using namespace Std;class Singleton {public:static singleton* Instance ();p Rotected:singleton ();p rivate:static singleton* _instance; }; singleton* singleton::_instance=0; Singleton::singleton () {cout<< "Singleton ..." <<endl;}; Singleton*singleton::instance () {if (_instance==0) {_instance=new Singleton ();} return _instance;} int main (int argc,char* argv[]) {singleton* sgn=singleton::instance (); return 0;}
The constructor for the singleton type must be protected to ensure that the type cannot be instantiated, and the static member function instance is used to instantiate the type. Because the function is static, each invocation is the same instance. This ensures that the singleton type can be instantiated once.

Copyright notice: This article blog original articles, blogs, without consent, may not be reproduced.

C + + Singleton

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.