C语言中如何实现单例模式?

2026-04-19 02:330阅读0评论SEO基础
  • 内容介绍
  • 文章标签
  • 相关推荐

本文共计1097个文字,预计阅读时间需要5分钟。

C语言中如何实现单例模式?

在编写C++代码时,经常使用单例模式以实现类对象的唯一实例。以下是一个简化版的单例模式实现:

cppnamespace tlanyan{ class Foo { private: static Foo* _instance;

public: Foo() {}

static Foo* getInstance() { if (_instance==NULL) { _instance=new Foo(); } return _instance; } };}

写C++的时候用到单例,于是很自然的写出如下的代码:

namespace tlanyan { class Foo { private: static Foo* _instance; Foo() {} // other members public: static Foo* getInstance() { if (_instance == NULL) { _instance = new Foo(); } return _instance; } ~Foo() { // clean codes } // other members and codes }; Foo* Foo::_instance = NULL; }

代码的本意:静态成员函数getInstance获取单例指针,并且在析构函数中做一些收尾工作。

阅读全文

本文共计1097个文字,预计阅读时间需要5分钟。

C语言中如何实现单例模式?

在编写C++代码时,经常使用单例模式以实现类对象的唯一实例。以下是一个简化版的单例模式实现:

cppnamespace tlanyan{ class Foo { private: static Foo* _instance;

public: Foo() {}

static Foo* getInstance() { if (_instance==NULL) { _instance=new Foo(); } return _instance; } };}

写C++的时候用到单例,于是很自然的写出如下的代码:

namespace tlanyan { class Foo { private: static Foo* _instance; Foo() {} // other members public: static Foo* getInstance() { if (_instance == NULL) { _instance = new Foo(); } return _instance; } ~Foo() { // clean codes } // other members and codes }; Foo* Foo::_instance = NULL; }

代码的本意:静态成员函数getInstance获取单例指针,并且在析构函数中做一些收尾工作。

阅读全文