c++基础:37.单例模式

cpp 复制代码
#include <iostream>
class Demo
{
	public:
	Demo(const Demo&)=delete;
	static Demo& Get()
	{
		static Demo demo;
		return demo;
	}
	private:
	Demo(){}
};

写一个生成随机数的单例类

cpp 复制代码
//Random.h
#pragma once
#include <random>
class Random
{
public:
	Random(const Random&) = delete;
	static Random& GetInstance();
	int GetNumber(int min, int max);
private:
	Random(){}
};
cpp 复制代码
//Random.cpp
#include "Random.h"
Random& Random::GetInstance()
{
	static Random random;
	return random;
}
int Random::GetNumber(int min, int max)
{
	std::random_device rd;
	std::mt19937 gen(rd());
	//随机数范围
	std::uniform_int_distribution<>dis(min, max);
	return dis(gen);
}
cpp 复制代码
//demo.cpp
#include <iostream>
#include "Random.h"
int main()
{
	for (int i = 0; i < 10; i++)
	{
		int num = Random::GetInstance().GetNumber(1, 100);
		std::cout << num << std::endl;
	}
	
	std::cin.get();
}

这是常规方式,每次使用都需要调用GetInstance()函数。这里可以使用另一种方法。

c 复制代码
//Random.h
#pragma once
#include <random>
class Random
{
public:
	Random(const Random&) = delete;
	static Random& GetInstance();
	//获取随机数
	static int Number(int min, int max);
	
private:
	int GetNumber(int min, int max);
	Random(){}
};
cpp 复制代码
//Random.cpp
#include "Random.h"


Random& Random::GetInstance()
{
	static Random random;
	return random;
}
int Random::GetNumber(int min, int max)
{
	std::random_device rd;
	std::mt19937 gen(rd());
	//随机数范围
	std::uniform_int_distribution<>dis(min, max);
	return dis(gen);
}
 int Random::Number(int min, int max)
{
	 return GetInstance().GetNumber(min, max);
}
cpp 复制代码
#include <iostream>
#include "Random.h"
int main()
{
	for (int i = 0; i < 10; i++)
	{
		std::cout << Random::Number(1,100) << std::endl;
	}
	
	std::cin.get();
}
相关推荐
草莓熊Lotso4 分钟前
【Linux网络】深入理解 HTTP 协议(一):从基础概念到 URL 编码解码
linux·网络·c++·网络协议·http·软件工程
眠りたいです4 分钟前
现代C++:C++17中的新语言特性
开发语言·c++·c++17
一只旭宝6 分钟前
【C++入门精讲17】序列容器
开发语言·c++
郝学胜-神的一滴12 分钟前
Qt 高级开发 021:零基础吃透 QVBoxLayout 垂直布局
开发语言·c++·qt·程序人生·用户界面
basketball61615 分钟前
C++进阶:2. std::move 和 std::forward 函数
java·开发语言·c++
玖釉-16 分钟前
LeetCode Hot 100 知识点总结与算法指南
c++·windows·算法·leetcode
Hall_IC19 分钟前
LSM6DS3TR-C现货询价丨粤科源兴ST代理商,专业FAE技术支持
c++
进击的荆棘21 分钟前
优选算法——队列+宽搜
数据结构·c++·算法·leetcode·bfs·队列
Irissgwe21 分钟前
STL简介
c++·stl