C ++ design mode: one of Singleton's template implementation

zhaozj2021-02-16  74

Title: C design mode: Singleton's template implementation type: original

Author: Gu Bin Liang time: 2002.12.25EMail: KingLinux@163.com

Looked two articles on design patterns: Singleton's C implemented article, consciously learned a lot of things (:)), I also wrote a C template here. One of the realizes, I hope that you will advise you prawn, but also hope that you can reach the role of pouring jade.

The principle of Singleton can refer to the "c design mode Singleton" or http://www.9cbs.net/, "Singleton mode C implementation research" or book "design mode", you don't say it here. Please bear with me!

Cuihua, on the code!

/// singleton template file // singleex.h

#ifndef singletonex__h __ # define Singletonex__h__

// File Name: SingletonEx.h // function: to provide a single piece of template functions (singleton template) // Copyright (C) C // Microsoft Visual C 6.0, GCC Ver2.95.3-6 compile // Author: Gu Bin Liang // Time: 2002.12.25 // email: kinglinux@163.com

Template class csingletonbase {protected: inline static t * create (void) {if (m_pt == null) {m_pt = new t ();} return m_pt;}

Inline static void free (void) {delete m_pt; m_pt = null;

protected: csingletonbase () {}

Virtual ~ csingletonbase () {delete m_pt;}

Private: csingletonbase (const csingletonbase & sig) {}

CSITONBASE & OPERATOR = (const csingletonbase & sig) {}

PRIVATE: STATIC T * m_pt;};

Template t * csingletonbase :: m_pt = null;

Template CSINGLETONEX: Private CsingletonBase {public: csingletoneX () {}

Virtual ~ csingletonex () {}

PUBLIC: Virtual T * Instance (void) {Return CsingletonBase :: Create ();

Virtual void release (void) {CSITONBASE :: free ();

Private: csingletonex (const csingletonex & sig) {}

CsingletoneX & Operator = (const csingletonex & sign {}};

#ENDIF // Singletonex__h__

// Test class //doc.h

#ifndef cdoc__h __ # define cdoc__h__

Class cdoc // Test class {public: cdoc (const st: string name = "noname"): m_name (name) {} virtual ~ cdoc () {} public: inline std :: string name () {return m_name; }

Inline void setname (const st :: string & name) {m_name = name;}

Protected: std :: string m_name;

#ENDIF / / CDOC__H__

// Test file //main.cpp

#include #include #include "singletonex.h" #include "doc.h"

Void Testsingletonex (void) {csingletonex s;

CDOC * pdoc = s.instance ();

Std :: cout << pdoc-> name () << std :: end1

PDOC-> SetName ("PDOC Change: My Singletonex");

Cdoc * p2 = s.instance ();

Std :: cout << p2-> name () << std :: endl;

P2-> SetName ("P2 Change: Singletonex");

Std :: cout << pdoc-> name () << std :: endl;

Void main (void) {std :: cout << "******** Test SingletoneX Start ******** << std :: endl; testsingletonex ();

// the end !!

转载请注明原文地址:https://www.9cbs.com/read-23978.html

New Post(0)