设计模式(5)——单例 Singleton

本文深入探讨了单例模式的设计理念,介绍了如何确保一个类只有一个实例并提供全局访问点的方法。文章详细讲解了单例模式的实现步骤,包括使用私有构造函数防止外部实例化以及通过静态方法提供对唯一实例的访问。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

目录:

设计模式学习笔记首页
设计模式(1)——抽象工厂 AbstractFactory
设计模式(2)——生成器 Builder
设计模式(3)——工厂方法 Factory Method
设计模式(4)——原型 Prototype
设计模式(5)——单例 Singleton
设计模式(6)——适配器 Adapter
设计模式(7)——桥接 Bridge
设计模式(8)——组合 Composite
设计模式(9)——装饰 Decorator
设计模式(10)——外观 Facade
设计模式(11)——享元 Flyweight
设计模式(12)——代理 Proxy
设计模式(13)——职责链 Chain Of Responsibility
设计模式(14)——命令 Command
设计模式(15)——解释器 Interpreter
设计模式(16)——迭代器 Iterator
设计模式(17)——中介者 Mediator
设计模式(18)——备忘录 Memento
设计模式(19)——观察者 Observer
设计模式(20)——状态 State
设计模式(21)——策略 Strategy
设计模式(22)——模板方法 Template Method
设计模式(23)——访问者 Visitor

五、Singleton (单例模式,对象创建型模式)

1. 问题:

  怎样创建一个唯一的变量(对象)?面向过程编程中可以创建一个全局变量(对象),纯粹面向对象中,可能只能通过 Singleton 模式来袜邮。

2. 功能:

  代替全局变量只生成一个实例

3. 意图:

  保证一个类仅有一个实例,并提供一个访问它的全局访问点。

4. 类图:

image

5. 中间层思考:

  单例模式在系统和全局变量之间添加了一个中间层。

6. 代码实现:

  1. 私有构造函数(禁用 new Singleton()
  2. 编写一个静态方法 getInstance() 返回 Singleton 实例
Singleton.h
// Singleton.h
#pragma once

#include <iostream>

using namespace std;

class Singleton {
public:
    static Singleton* getInstance();
private:
    Singleton();
    static Singleton* instance;
};

Singleton.cpp

// Singleton.cpp
#include "Singleton.h"

#include <iostream>

using namespace std;

Singleton* Singleton::instance = 0;

Singleton::Singleton() {
    cout << "Singleton..." << endl;
}

Singleton* Singleton::getInstance() {
    if (instance == 0) {
        instance = new Singleton();
    }
    return instance;
}

main.cpp

// main.cpp
#include "Singleton.h"

#include <iostream>

using namespace std;

int main(int argc, char* argv[]) {
    Singleton* sgn = Singleton::getInstance();
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值