目录:
设计模式学习笔记首页
设计模式(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. 类图:
5. 中间层思考:
单例模式在系统和全局变量之间添加了一个中间层。
6. 代码实现:
- 私有构造函数(禁用
new Singleton()
) - 编写一个静态方法
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;
}