当前位置: 首页 > news >正文

C++八大常见的设计模式的实现与实践指南

目录

  1. 创建型模式
    • 单例模式
    • 工厂方法模式
    • 抽象工厂模式
  2. 结构型模式
    • 适配器模式
    • 装饰者模式
    • 代理模式
  3. 行为型模式
    • 观察者模式
    • 策略模式
    • 命令模式
  4. 高级主题
    • 现代C++特性影响
    • 模式性能对比
    • 典型应用案例

设计模式分类
在这里插入图片描述

一、创建型模式

1. 单例模式(Singleton)

现代C++17线程安全实现
#include <mutex>
#include <memory>class ConfigManager {
private:static std::unique_ptr<ConfigManager> instance;static std::once_flag initFlag;// 私有构造函数ConfigManager() { loadConfig(); }void loadConfig() { /* 加载配置文件 */ }public:// 删除拷贝操作ConfigManager(const ConfigManager&) = delete;ConfigManager& operator=(const ConfigManager&) = delete;static ConfigManager& getInstance() {std::call_once(initFlag, [](){instance.reset(new ConfigManager);});return *instance;}std::string getValue(const std::string& key) { /* 返回配置值 */ return "";}
};// 初始化静态成员
std::unique_ptr<ConfigManager> ConfigManager::instance;
std::once_flag ConfigManager::initFlag;
应用陷阱
  • 测试困难:全局状态影响单元测试
  • 生命周期管理:依赖顺序问题
  • 多线程初始化竞争

2. 工厂方法模式(Factory Method)

现代实现(使用lambda工厂)
#include <functional>
#include <map>class Button {
public:virtual void render() = 0;virtual ~Button() = default;
};class WindowsButton : public Button {
public:void render() override { /* Windows风格渲染 */ }
};class MacButton : public Button {
public:void render() override { /* Mac风格渲染 */ }
};class GUIFactory {
private:using FactoryFunc = std::function<std::unique_ptr<Button>()>;std::map<std::string, FactoryFunc> factories;public:void registerFactory(const std::string& type, FactoryFunc factory) {factories[type] = factory;}std::unique_ptr<Button> createButton(const std::string& type) {if (auto it = factories.find(type); it != factories.end())return it->second();throw std::runtime_error("Unknown button type");}
};// 使用示例
GUIFactory factory;
factory.registerFactory("Windows", []{ return std::make_unique<WindowsButton>(); });
factory.registerFactory("Mac", []{ return std::make_unique<MacButton>(); });auto btn = factory.createButton("Windows");
btn->render();

二、结构型模式

3. 适配器模式(Adapter)

对象适配器实现
// 遗留圆形接口
class LegacyCircle {
public:void draw(int x, int y, int radius) {// 绘制圆形实现}
};// 新系统需要的形状接口
class Shape {
public:virtual void draw(float x, float y, float size) = 0;virtual ~Shape() = default;
};class CircleAdapter : public Shape {LegacyCircle legacyCircle;
public:void draw(float x, float y, float size) override {// 转换参数并调用遗留接口legacyCircle.draw(static_cast<int>(x), static_cast<int>(y),static_cast<int>(size/2));}
};

4. 装饰者模式(Decorator)

流处理装饰器
#include <iostream>
#include <memory>class DataStream {
public:virtual void write(const std::string& data) = 0;virtual ~DataStream() = default;
};class FileStream : public DataStream {
public:void write(const std::string& data) override {std::cout << "Writing to file: " << data << "\n";}
};class StreamDecorator : public DataStream {
protected:std::unique_ptr<DataStream> wrapped;
public:StreamDecorator(std::unique_ptr<DataStream> stream): wrapped(std::move(stream)) {}
};class CompressionDecorator : public StreamDecorator {
public:using StreamDecorator::StreamDecorator;void write(const std::string& data) override {auto compressed = compress(data);wrapped->write(compressed);}private:std::string compress(const std::string& data) {return "COMPRESSED[" + data + "]";}
};// 使用组合
auto stream = std::make_unique<CompressionDecorator>(std::make_unique<FileStream>()
);
stream->write("Sample Data");

二、结构型模式(续)

5. 代理模式(Proxy)

定义:为其他对象提供一种代理以控制对这个对象的访问

应用场景

  • 延迟初始化(虚拟代理)
  • 访问控制(保护代理)
  • 本地执行远程服务(远程代理)
  • 日志记录(日志代理)

现代C++实现(延迟加载代理)

class Image {
public:virtual void display() = 0;virtual ~Image() = default;
};class HighResImage : public Image {std::string filename;
public:HighResImage(const std::string& file) : filename(file) {loadFromDisk();}void display() override {std::cout << "Displaying " << filename << "\n";}private:void loadFromDisk() {std::cout << "Loading " << filename << " from disk...\n";}
};class ImageProxy : public Image {std::unique_ptr<HighResImage> realImage;std::string filename;
public:ImageProxy(const std::string& file) : filename(file) {}void display() override {if (!realImage) {realImage = std::make_unique<HighResImage>(filename);}realImage->display();}
};// 使用示例
std::vector<std::unique_ptr<Image>> images;
images.push_back(std::make_unique<ImageProxy>("photo1.jpg"));
images.push_back(std::make_unique<ImageProxy>("photo2.jpg"));// 只有在实际显示时才加载图片
images[0]->display();  // 输出加载信息
images[0]->display();  // 直接显示,不再加载

三、行为型模式

6. 观察者模式(Observer)(续)

现代C++改进(类型安全实现)

#include <vector>
#include <functional>
#include <memory>template <typename... Args>
class Observable {using Observer = std::function<void(Args...)>;std::vector<std::weak_ptr<Observer>> observers;public:auto registerObserver(Observer callback) {auto shared = std::make_shared<Observer>(std::move(callback));observers.emplace_back(shared);return shared;}void notify(Args... args) {auto it = observers.begin();while (it != observers.end()) {if (auto observer = it->lock()) {(*observer)(args...);++it;} else {it = observers.erase(it);}}}
};// 使用示例
class Sensor {
public:Observable<float> temperatureChanged;void updateTemperature(float temp) {currentTemp = temp;temperatureChanged.notify(temp);}private:float currentTemp;
};int main() {Sensor sensor;auto observer = sensor.temperatureChanged.registerObserver([](float temp) {std::cout << "Temperature updated: " << temp << "°C\n";});sensor.updateTemperature(23.5f);sensor.updateTemperature(24.1f);
}

7. 策略模式(Strategy)

定义:定义算法族,分别封装,使它们可以互相替换

现代C++实现(使用std::function)

#include <functional>
#include <vector>class SortStrategy {
public:virtual void sort(std::vector<int>& data) = 0;virtual ~SortStrategy() = default;
};// 传统实现方式
class BubbleSort : public SortStrategy {
public:void sort(std::vector<int>& data) override {// 实现冒泡排序}
};// 现代C++风格实现
using ModernSortStrategy = std::function<void(std::vector<int>&)>;class SortContext {
public:// 传统策略方式void setStrategy(std::unique_ptr<SortStrategy> strategy) {this->strategy = std::move(strategy);}// 现代策略方式void setModernStrategy(ModernSortStrategy strategy) {modernStrategy = std::move(strategy);}void executeSort(std::vector<int>& data) {if (modernStrategy) {modernStrategy(data);} else if (strategy) {strategy->sort(data);}}private:std::unique_ptr<SortStrategy> strategy;ModernSortStrategy modernStrategy;
};// 使用示例
int main() {std::vector<int> data = {5, 2, 7, 1, 9};// 传统方式SortContext context1;context1.setStrategy(std::make_unique<BubbleSort>());context1.executeSort(data);// 现代方式SortContext context2;context2.setModernStrategy([](std::vector<int>& data) {// 实现快速排序std::sort(data.begin(), data.end());});context2.executeSort(data);
}

8. 命令模式(Command)

定义:将请求封装为对象,支持撤销操作

完整实现(含撤销功能)

#include <vector>
#include <memory>
#include <stack>class Document {std::string content;
public:void addText(const std::string& text) {content += text;}void deleteText(size_t length) {if (length >= content.size()) {content.clear();} else {content.erase(content.size() - length);}}std::string getContent() const { return content; }
};class Command {
public:virtual void execute() = 0;virtual void undo() = 0;virtual ~Command() = default;
};class AddTextCommand : public Command {Document& doc;std::string addedText;
public:AddTextCommand(Document& d, std::string text): doc(d), addedText(std::move(text)) {}void execute() override {doc.addText(addedText);}void undo() override {doc.deleteText(addedText.size());}
};class CommandHistory {std::stack<std::unique_ptr<Command>> history;
public:void push(std::unique_ptr<Command> cmd) {cmd->execute();history.push(std::move(cmd));}void undo() {if (!history.empty()) {history.top()->undo();history.pop();}}
};// 使用示例
int main() {Document doc;CommandHistory history;history.push(std::make_unique<AddTextCommand>(doc, "Hello "));history.push(std::make_unique<AddTextCommand>(doc, "World!"));std::cout << doc.getContent() << "\n";  // 输出:Hello World!history.undo();std::cout << doc.getContent() << "\n";  // 输出:Hello history.undo();std::cout << doc.getContent() << "\n";  // 输出:(空)
}

四、高级主题

1. 现代C++特性对设计模式的重构

1.1 Lambda表达式与策略模式融合
class PaymentProcessor {
public:using PaymentStrategy = std::function<bool(float)>;void setStrategy(PaymentStrategy strategy) {currentStrategy = std::move(strategy);}bool processPayment(float amount) {if(currentStrategy) {return currentStrategy(amount);}throw std::runtime_error("No payment strategy set");}private:PaymentStrategy currentStrategy;
};// 使用示例
PaymentProcessor processor;
processor.setStrategy([](float amount) -> bool {// 信用卡支付实现return true; 
});processor.processPayment(99.99f);
1.2 可变参数模板实现通用装饰者
template <typename Component>
class LoggerDecorator {Component wrapped;
public:LoggerDecorator(Component&& comp) : wrapped(std::forward<Component>(comp)) {}template <typename... Args>auto operator()(Args&&... args) {std::cout << "Calling function with args: " << sizeof...(args) << "\n";auto result = wrapped(std::forward<Args>(args)...);std::cout << "Return value: " << result << "\n";return result;}
};// 用法示例
auto decoratedFunc = LoggerDecorator([](int x, int y) { return x + y; });
decoratedFunc(3, 4);  // 输出调用日志和结果

2. 设计模式性能对比分析

2.1 虚函数调用开销测试
#include <chrono>// 传统策略模式实现
class TraditionalStrategy {
public:virtual int compute(int x) = 0;virtual ~TraditionalStrategy() = default;
};// 现代策略实现
using ModernStrategy = std::function<int(int)>;// 性能测试函数
template <typename Strategy>
void runBenchmark(Strategy&& strategy) {constexpr int iterations = 1'000'000;auto start = std::chrono::high_resolution_clock::now();int sum = 0;for(int i = 0; i < iterations; ++i) {sum += strategy(i);}auto duration = std::chrono::duration_cast<std::chrono::microseconds>(std::chrono::high_resolution_clock::now() - start);std::cout << "Time: " << duration.count() << "μs\n";
}// 测试用例
struct AddStrategy : TraditionalStrategy {int compute(int x) override { return x + 1; }
};int main() {// 传统虚函数调用AddStrategy traditional;runBenchmark([&](int x) { return traditional.compute(x); });// 现代std::functionModernStrategy modern = [](int x) { return x + 1; };runBenchmark(modern);// 直接lambda调用runBenchmark([](int x) { return x + 1; });
}

典型结果

  • 传统虚函数调用:约850μs
  • std::function调用:约780μs
  • 直接lambda调用:约650μs

3. 设计模式在游戏引擎中的实践

3.1 组件模式实现游戏对象系统
class GameObject {std::unordered_map<std::type_index, std::unique_ptr<Component>> components;public:template <typename T, typename... Args>T& addComponent(Args&&... args) {auto ptr = std::make_unique<T>(std::forward<Args>(args)...);auto& ref = *ptr;components[typeid(T)] = std::move(ptr);return ref;}template <typename T>T* getComponent() {auto it = components.find(typeid(T));return (it != components.end()) ? static_cast<T*>(it->second.get()) : nullptr;}void update() {for(auto& [_, comp] : components) {comp->update();}}
};class Component {
public:virtual void update() = 0;virtual ~Component() = default;
};// 具体组件实现
class Transform : public Component {
public:void update() override { /* 更新位置信息 */ }
};class PhysicsBody : public Component {
public:void update() override { /* 物理模拟计算 */ }
};// 使用示例
GameObject player;
player.addComponent<Transform>();
player.addComponent<PhysicsBody>();
player.update();

3.2 状态模式实现角色行为控制
class CharacterState {
public:virtual void enter() = 0;virtual void handleInput(char input) = 0;virtual void update() = 0;virtual ~CharacterState() = default;
};class IdleState : public CharacterState {
public:void enter() override { std::cout << "Entering Idle\n"; }void handleInput(char input) override {if(input == 'w') /* 切换到移动状态 */;}void update() override { /* 闲置动画更新 */ }
};class StateMachine {std::unique_ptr<CharacterState> currentState;
public:void changeState(std::unique_ptr<CharacterState> newState) {if(currentState) currentState->exit();newState->enter();currentState = std::move(newState);}void update() {if(currentState) currentState->update();}
};// 使用示例
StateMachine fsm;
fsm.changeState(std::make_unique<IdleState>());while(true) {char input = getInput();fsm.handleInput(input);fsm.update();
}

五、设计模式最佳实践指南

1. 模式选择决策树

是否需要控制对象创建?
├─ 是 → 考虑工厂/建造者模式
├─ 否 → 是否需要扩展对象功能?
│    ├─ 是 → 装饰者/代理模式
│    └─ 否 → 是否需要算法切换?
│         ├─ 是 → 策略模式
│         └─ 否 → 是否需要状态管理?
│              ├─ 是 → 状态模式
│              └─ 否 → 观察者/命令模式

2. 典型代码异味与模式对应

代码问题推荐模式重构示例
多重条件分支策略/状态模式用多态替代switch-case
接口不兼容适配器模式包装旧接口为新接口
过度全局访问单例→依赖注入引入服务定位器
难以扩展功能装饰者/组合模式动态添加组件
紧耦合的对象通信观察者/中介者模式事件驱动架构

3. 现代C++设计原则

  1. 优先组合而非继承:使用std::variant/std::any实现运行时多态
  2. 利用RAII管理资源:智能指针自动管理模式对象生命周期
  3. 编译时多态优化:模板方法替代运行时虚函数分派
  4. 移动语义优化性能:在工厂模式中高效转移大型对象
  5. 类型擦除技术:使用std::function实现灵活的策略模式

六、常见陷阱与调试技巧

1. 单例模式的内存泄漏检测

使用Valgrind或AddressSanitizer检测未释放实例:

$ g++ -fsanitize=address -g singleton.cpp
$ ASAN_OPTIONS=detect_leaks=1 ./a.out

2. 观察者模式的循环引用排查

使用weak_ptr打破强引用循环:

class Subject {std::vector<std::weak_ptr<Observer>> observers;public:void addObserver(std::weak_ptr<Observer> obs) {observers.push_back(obs);}void notify() {for(auto& weakObs : observers) {if(auto obs = weakObs.lock()) {obs->update();}}}
};

3. 工厂模式的类型注册验证

静态断言确保类型安全:

template <typename T>
void registerType() {static_assert(std::is_base_of_v<BaseProduct, T>, "Must inherit from BaseProduct");// 注册逻辑...
}

七、延伸阅读与工具推荐

1. 进阶学习资源

  • 《Modern C++ Design》Andrei Alexandrescu
  • 《C++ Core Guidelines》设计模式章节
  • CppCon会议演讲:Modern C++ Design Patterns

2. 可视化设计工具

  • PlantUML:模式UML图生成
  • Doxygen:模式文档自动化
  • Clang-Query:模式代码静态检测

3. 性能分析工具链

工具名称用途示例命令
Perf函数级热点分析perf record ./app
Hotspot可视化性能数据图形化展示perf结果
Cachegrind缓存访问模式分析valgrind --tool=cachegrind ./app

相关文章:

C++八大常见的设计模式的实现与实践指南

目录 创建型模式 单例模式工厂方法模式抽象工厂模式 结构型模式 适配器模式装饰者模式代理模式 行为型模式 观察者模式策略模式命令模式 高级主题 现代C特性影响模式性能对比典型应用案例 设计模式分类 一、创建型模式 1. 单例模式&#xff08;Singleton&#xff09; 现代…...

02 windows qt配置ffmpeg开发环境搭建

版本说明 首先我使用ffmpeg版本是4.2.1QT使用版本5.14.2我选择是c编译...

什么是状态管理?有何种方式可以实现?它们之间有什么区别?

目录 一、状态管理的核心概念 二、常见状态管理方案及对比 1. 基础方案:setState 2. 官方推荐:Provider 3. 事件驱动:Bloc (Business Logic Component) 4. 响应式增强:Riverpod 5. 轻量级全能库:GetX 三、方案对比与选型指南 四、实战建议 在 Flutter 中,状态管…...

tf1.x和tf2.x在使用上的区别和联系是什么

tf1.x和tf2.x在使用上的区别和联系是什么 TensorFlow 1.x 和 2.x 在使用上有显著差异&#xff0c;主要体现在编程范式、API 设计和易用性上&#xff0c;但二者仍共享相同的核心目标&#xff08;深度学习框架&#xff09;和底层计算引擎。以下是主要区别和联系&#xff1a; 主要…...

Elasticsearch使用记录

一、配环境 1.docker版本部署es 8.x系列可以关掉ssl&#xff08;本地测试时&#xff09;&#xff0c;去docker的/usr/share/elasticsearch/config/elasticsearch.yml里面的“xpack.security.enabled:”设置成true就可以 2.window docker部署推荐教程&#xff1a;基于Docker安…...

【python web】一文掌握 Flask 的基础用法

文章目录 一、 Flask 介绍1.1 安装 Flask二、Flask的基本使用2.1 创建第一个 Flask 应用2.2 路由与视图函数2.3 请求与响应2.4 响应对象2.5 模板渲染2.6 模板继承2.7 静态文件管理2.8 Blueprint 蓝图2.9 错误处理三、Flask扩展与插件四、部署 Flask 应用五、总结Flask 是一个轻…...

第十六届蓝桥杯单片机组4T模拟赛二

难点&#xff1a; PCF8591同时测量两条通道数据 避免重复触发 采集触发时的时间数据存放 未采集的数据显示 清空数据 本题建议了解怎么去触发采集&#xff0c;怎么显示最近三次触发采集的时间即可。由于4T模拟赛的尿性有很多评测点是题目中没有要求的&#xff0c;另外测评的时候…...

《解锁华为黑科技:MindSpore+鸿蒙深度集成奥秘》

在数字化浪潮汹涌澎湃的当下&#xff0c;人工智能与操作系统的融合已成为推动科技发展的核心驱动力。华为作为科技领域的先锋&#xff0c;其AI开发框架MindSpore与鸿蒙系统的深度集成备受瞩目&#xff0c;开启了智能生态的新篇章。 华为MindSpore&#xff1a;AI框架的创新先锋…...

kotlin中的list set map整理

在 Kotlin 中&#xff0c;List、Set 和 Map 是三种核心集合类型&#xff0c;它们分别适用于不同的场景&#xff0c;具有独特的特性和操作方式。以下是它们的详细对比与使用指南&#xff1a; 1. List&#xff08;列表&#xff09; 核心特性 • 有序&#xff1a;元素按插入顺序…...

条款43:学习处理模板化基类内的名称

前提认知&#xff1a;模板类继承模板类&#xff0c;是需要建立在假设的前提下的&#xff0c;如果没有这个”假设“&#xff0c;编译将会失败 1.书上举例 2.完整代码举例 #include <iostream>class MsgInfo { };class BaseCompany { public:BaseCompany(){}~BaseCompan…...

五种方案实现双链路可靠数据传输

本文介绍五种双链路数据传输方案,目标是利用设备的多个传输通道,(如双有线网口,网口+wifi, 网口+5G等场景 , 网口+ 自组网, 自组网 + 5G等),将数据复制后分流、分路同时传输,以期提高数据传输可靠性,满足高可靠性传输的应用场景需求。部分方案给出了实际验证结果 。 …...

提升AI性能的秘密武器:量化、蒸馏与剪枝全面解析

通过高效的模型压缩技术推进 NLP 在快速发展的自然语言处理 (NLP) 领域,模型的大小和复杂性显著增加,从而显著提高了性能。然而,这些庞大模型的部署和维护也带来了挑战,特别是在计算成本、功耗和资源受限用户的可访问性方面。本博客深入探讨了量化、剪枝和蒸馏等尖端模型压…...

React Native 如何使用 Expo 快速开发?

React Native是当下热门的跨平台移动开发框架&#xff0c;而Expo则是它的重要开发工具之一。Expo提供了一套完整的开发环境&#xff0c;使开发者无需安装Android Studio或Xcode也能快速运行React Native项目。它包含了众多内置API&#xff0c;如相机、地理位置、推送通知等&…...

C++Primer 拷贝控制示例

欢迎阅读我的 【CPrimer】专栏 专栏简介&#xff1a;本专栏主要面向C初学者&#xff0c;解释C的一些基本概念和基础语言特性&#xff0c;涉及C标准库的用法&#xff0c;面向对象特性&#xff0c;泛型特性高级用法。通过使用标准库中定义的抽象设施&#xff0c;使你更加适应高级…...

Qt 读取数据库

在 Qt 中读取数据库文件通常涉及以下步骤。这里以 SQLite 为例&#xff08;Qt 内置支持&#xff09;&#xff0c;其他数据库&#xff08;如 MySQL、PostgreSQL&#xff09;需要对应驱动&#xff1a; 1. 添加 SQL 模块依赖 在项目文件 .pro 中添加&#xff1a; QT sql2. 基本…...

DeepSeek在学术研究方向初期工作提示词分享

目录 论文选题 研读文献 拟定提纲 大家好这里是AIWritePaper官方账号&#xff01;更多内容&#x1f449;AIWritePaper~在如今这个学术圈的“快车道”上&#xff0c;时间就像是一场永不停歇的赛跑&#xff0c;而论文质量则是那颗我们拼命追逐的“金苹果”。最近一款名为DeepS…...

CentOS下安装ElasticSearch(日志分析)

准备目录 搞一个自己喜欢的目录 mkdir /usr/local/app 切换到该目录 cd /usr/local/app 下载 wget https://artifacts.elastic.co/downloads/elasticsearch/elasticsearch-7.9.2-linux-x86_64.tar.gz 选择其他版本 点击进入官网...

科技云报到:AI Agent打了个响指,商业齿轮加速转动

科技云报到原创。 3月16日&#xff0c;百度旗下文心大模型4.5和文心大模型X1正式发布。目前&#xff0c;两款模型已在文心一言官网上线&#xff0c;免费向用户开放。 同时&#xff0c;文心大模型4.5已上线百度智能云千帆大模型平台&#xff0c;企业用户和开发者登录即可调用AP…...

布谷直播系统源码开发实战:从架构设计到性能优化

作为山东布谷科技的一名技术研发人员&#xff0c;我参与了多个直播系统平台从0到1的开发和搭建&#xff0c;也见证了直播行业从萌芽到爆发的全过程。今天&#xff0c;我想从研发角度&#xff0c;分享一些直播系统软件开发的经验和心得&#xff0c;希望能对大家有所帮助。 一、 …...

pytorch小记(十):pytorch中torch.tril 和 torch.triu 详解

pytorch小记&#xff08;十&#xff09;&#xff1a;pytorch中torch.tril 和 torch.triu 详解 PyTorch torch.tril 和 torch.triu 详解1. torch.tril&#xff08;计算下三角矩阵&#xff09;&#x1f4cc; 作用&#x1f50d; 语法&#x1f539; 参数&#x1f4cc; 示例&#x1…...

C语言每日一练——day_11

引言 针对初学者&#xff0c;每日练习几个题&#xff0c;快速上手C语言。第十一天。&#xff08;连续更新中&#xff09; 采用在线OJ的形式 什么是在线OJ&#xff1f; 在线判题系统&#xff08;英语&#xff1a;Online Judge&#xff0c;缩写OJ&#xff09;是一种在编程竞赛中…...

HCIA-PPP实验

一、LCP链路控制协议 1、链路建立阶段&#xff1a;通过交互LCP报文协商参数&#xff0c;包含了MRU、认证类型、魔术字等。 2、链路维护阶段&#xff1a; 3、链路终止 二、NCP网络控制协议&#xff1a;交互PPP IPCP报文,检测地址、学习路由、下发地址 1、通过IPCP协议的请求消…...

C++学习之云盘项目nginx

1.复习 2.知识点概述 1. 一些基本概念 1.1 Nginx 初步认识 1.2 正向 / 反向代理 1.3 域名和 IP 2. Nginx 安装和配置 2.1 安装 2.2 配置 3. Nginx 的使用 3.1 部署静态网页 3.2 反向代理和负载均衡 课外知识导读 1. URL 和 URI 2. DNS 解析过程 1. 一些基…...

7-字符串

1-ASCII 0-9 对应 48-57 A-Z 对应 65-90 a-z 对应 97-122 2-字符数组 字符变量存储单个字符 字符数组存储多个字符 字符串就是字符数组加上结束符 ’ \0 ’ #include <iostream> using namespace std; int main(){//是字符数组&#xff0c;不是字符串char a1[]{C,,};…...

vue学习八

十七 组件通信方式 1 props 父传子 //父组件 <script setup>//book来源省略import Subview1 from ./Subview1.vue;function updatebook(updatetimes){book.value.updatetimes updatetimes} </script> <template><Subview1 :book"book" :upd…...

Vue 渲染 LaTeX 公式 Markdown 库

&#x1f31f; 前言 欢迎来到我的技术小宇宙&#xff01;&#x1f30c; 这里不仅是我记录技术点滴的后花园&#xff0c;也是我分享学习心得和项目经验的乐园。&#x1f4da; 无论你是技术小白还是资深大牛&#xff0c;这里总有一些内容能触动你的好奇心。&#x1f50d; &#x…...

基于大模型的喉癌全程预测与治疗方案优化研究报告

目录 一、引言 1.1 研究背景与意义 1.2 研究目的与目标 1.3 研究方法与数据来源 二、大模型在喉癌预测中的应用原理 2.1 大模型概述 2.2 预测喉癌的技术原理 2.3 相关技术对比 三、术前预测与方案制定 3.1 术前风险预测 3.1.1 淋巴结转移预测 3.1.2 其他风险因素预…...

SpringBoot第三站:配置嵌入式服务器使用外置的Servlet容器

目录 1. 配置嵌入式服务器 1.1 如何定制和修改Servlet容器的相关配置 1.server.port8080 2. server.context-path/tx 3. server.tomcat.uri-encodingUTF-8 1.2 注册Servlet三大组件【Servlet&#xff0c;Filter&#xff0c;Listener】 1. servlet 2. filter 3. 监听器…...

通向AGI的未来之路!首篇2D/视频/3D/4D统一生成框架全景综述(港科大中山等)

文章链接&#xff1a; https://arxiv.org/pdf/2503.04641 摘要 理解并复现现实世界是人工通用智能&#xff08;AGI&#xff09;研究中的一个关键挑战。为实现这一目标&#xff0c;许多现有方法&#xff08;例如世界模型&#xff09;旨在捕捉支配物理世界的基本原理&#xff0…...

什么是MCP(Model Context Protocol)?对话、意图识别、服务调用和上下文管理

什么是MCP&#xff1f; MCP&#xff08;Model Context Protocol&#xff09; 是一种专为人工智能模型设计的通信协议&#xff0c;旨在解决复杂 AI 系统中多个模型或组件之间的协同、状态管理和资源优化问题。它尤其适用于大型语言模型&#xff08;LLM&#xff09;、多模态系统及…...

第二十七篇 数据仓库与维度建模指南:从理论到实战的进阶之路

声明&#xff1a;文章内容仅供参考&#xff0c;需仔细甄别。文中技术名称属相关方商标&#xff0c;仅作技术描述&#xff1b;代码示例为交流学习用途&#xff0c;部分参考开源文档&#xff08;Apache 2.0/GPLv3&#xff09;&#xff1b;案例数据已脱敏&#xff0c;技术推荐保持…...

定时任务引起的死锁

定时任务引起的死锁 前言&#xff1a;Java面试题 死锁的场景有哪些&#xff1f;你们是怎么解决的&#xff1f; 锁有哪些特性&#xff1f; 问题现象 1&#xff0c;文件上传报当前功能正在使用&#xff0c;请稍后再试 2&#xff0c;其他账号登录系统&#xff0c;登录不上去&a…...

NewStar CTF web wp

文章目录 week1headach3会赢吗智械危机谢谢皮蛋PangBai 过家家&#xff08;1&#xff09; week3include meblindsql1臭皮的计算机臭皮踩踩背这照片是你吗 week4Pangbai过家家四blindsql2chocolateezcmsssezpollute隐藏的密码 weeek5pangbai过家家(5)redissqlshell臭皮吹泡泡臭皮…...

Docker运行postgreSQL,由于异常启动或者退出后,提示could not locate a valid checkpoint record

pg_resetwal 是 PostgreSQL 的“急救工具”&#xff0c;用于在极端情况下修复因 WAL 或控制文件损坏导致的启动问题。 但需注意&#xff1a; 风险极高&#xff0c;可能导致数据不一致。必须立即转储并恢复&#xff0c;避免直接在修复后的数据库中执行写操作。仅在备份后使用&…...

Leetcode 刷题笔记1 图论part01

图论的基础知识&#xff1a; 图的种类&#xff1a; 有向图&#xff08;边有方向&#xff09; 、 无向图&#xff08;边无方向&#xff09;、加权有向图&#xff08;边有方向和权值&#xff09; 度&#xff1a; 无向图中几条边连接该节点&#xff0c;该节点就有几度&#xff1…...

文件管理系统

前言&#xff1a;之前我们讨论的是被打开文件的管理&#xff0c;那么未被打开的文件是如何管理的呢&#xff1f; 1.认识磁盘设备 1.1磁盘的物理结构 磁盘是由盘片&#xff08;盘面&#xff0c;扇区&#xff0c;磁道&#xff0c;柱面&#xff09;&#xff0c;磁头&#xff0c…...

荣耀手机卸载应用商店、快应用中心等系统自带的

1.下载abd ADB Download - Get the latest version of ADB and fastboot 2.手机打开开发者选项 3.手机接电脑打开USB调试 4.下载MT管理器查看系统包名 D:\1.LFD\ADB\platform-tools-latest-windows\platform-tools>adb shell adb.exe: no devices/emulators found 这边是…...

结合基于标签置信度的特征选择方法用于部分多标签学习-简介版

假设 部分多标签学习&#xff08;PML&#xff09;假设&#xff1a;假设样本的标签集合中存在伪正标签&#xff0c;即某些标签可能是错误的。目标是从候选标签集中识别出真实标签。特征与标签的关系假设&#xff1a;假设不同的标签对应的特征子空间可能是不同的&#xff0c;而不…...

【小白向】Word|Word怎么给公式标号、调整公式字体和花括号对齐

【小白向】Word&#xff5c;Word怎么给公式标号、调整公式字体和花括号对齐 我的版本&#xff1a;Word 2021 如需快速查看关键步骤&#xff0c;请直接阅读标红部分。 如果遇到无法调整的情况&#xff0c;可以直接下载我的示例文档进行参考&#xff1a;花括号和其他的示例公式.…...

基于香橙派 KunpengPro学习CANN(2)——Ascend Extension for PyTorch 配置与安装

将 PyTorch 网络迁移到昇腾平台并执行训练或推理&#xff0c;直接使用昇腾提供的构图接口构图。Ascend Extension for PyTorch插件用于适配PyTorch框架&#xff0c;可以使用昇腾AI处理器的算力。 1 pip 安装 # 下载PyTorch安装包 wget https://download.pytorch.org/whl/cpu/…...

【备赛】遇到的小问题-1

问题描述-1 想实现的功能是&#xff0c;通过ADC实时测量某引脚的电压及其占空比。 可以通过旋转电位器&#xff0c;更改其电压。 首先我定义了这几个变量 uint32_t adc_value;//HAL库函数里面得出的采样值(实时更新) uint32_t percentage6;//占空比&#xff0c;随着adc_val…...

Browser Use的安装和使用

文章目录 一、介绍二、安装教程1、使用Conda创建虚拟环境2、激活环境3、安装browser use4、安装Playwright5、克隆git仓库6、安装项目的依赖 三、使用教程1、启动WebUI2、案例13、案例2 一、介绍 背景 Browser Use&#xff1a;用AI控制你的浏览器&#xff0c;你可以使用它帮你…...

碰一碰发视频saas系统技术源头一站式开发文档

碰一碰发视频系统技术源头一站式开发文档 一、引言 在数字化信息传播高速发展的当下&#xff0c;如何让视频分享更便捷、高效&#xff0c;成为商家和开发者们关注的焦点。“碰一碰发视频”系统以其独特的交互方式和强大的功能优势&#xff0c;为视频分享领域带来了革命性变革。…...

Spring Boot 静态访问配置属性的解决方案

前言 在Spring Boot开发中&#xff0c;静态访问配置信息是一个常见需求&#xff0c;尤其是在工具类、常量类或非Bean类中直接获取配置值。 问题背景 假设我们的应用需要从application.yml中读取配置项app.logotype&#xff0c;并在工具类、静态方法或非Bean类中直接访问该值。…...

NLP高频面试题(四)——BN和LN的区别与联系,为什么attention要用LN

在深度学习模型中&#xff0c;Normalization是一种极为重要的技巧&#xff0c;Batch Normalization&#xff08;BN&#xff09;和Layer Normalization&#xff08;LN&#xff09;是其中最为常用的两种方法。然而&#xff0c;二者在实际应用中有着明显的区别与联系&#xff0c;尤…...

深度学习定义与分类【详细易懂 初学者友好~】

深度学习&#xff08;Deep Learning&#xff09;是机器学习的一个子领域&#xff0c;它基于人工神经网络&#xff08;Artificial Neural Networks&#xff0c;ANN&#xff09;的理论和架构&#xff0c;通过构建多层&#xff08;即“深度”&#xff09;的神经网络结构来学习数据…...

二、小白学JAVA-认识数据类型【变量】

1、实际案例类比 初中以上数学&#xff0c;就知道有有理数、正数、负数、0、小数、大写的数字、语文。 2、数据类型介绍 public class Main {public static void main(String[] args) {// 数据类型byte i_byte 12; // 标识数据范围小&#xff0c;但是节省内存>网络传输…...

UNI-APP uts插件 支持ANDROID 监听手机状态

插件地址 https://ext.dcloud.net.cn/plugin?id22646 模块 import {startPhoneListener,stopPhoneListener,checkIsAutoRecord,toCallAutoRecorderPage,navigateToCallRecordingSettings,jumpToPermissionPage,makePhoneCall,allRecorderFilesAction,registerSmsReceiver,} f…...

AI入门7:python三种API方式调用本地Ollama+DeepSeek

回顾 书接上篇&#xff1a;各种方式搭建了本地知识库&#xff1a; AI入门&#xff1a;AI模型管家婆ollama的安装和使用-CSDN博客 AI入门2&#xff1a;本地AI部署&#xff0c;用ollama部署deepseek&#xff08;私有化部署&#xff09;-CSDN博客 AI入门3&#xff1a;给本地d…...

SQL SERVER日常运维巡检系列—结构设计

前言   做好日常巡检是数据库管理和维护的重要步骤&#xff0c;而且需要对每次巡检日期、结果进行登记&#xff0c;同时可能需要出一份巡检报告。   本系列旨在解决一些常见的困扰&#xff1a; 不知道巡检哪些东西 不知道怎么样便捷体检 机器太多体检麻烦 生成报告…...