c++之策略模式
发布日期:2021-09-25 21:40:50
浏览次数:11
分类:技术文章
本文共 1052 字,大约阅读时间需要 3 分钟。
策略模式是行为型模式,它是一种定义一系列算法的方法,所有的这些算法完成的都是相同的工作,只是实现不同。所以可以用相同的方式去调用所有的算法,降低了算法类与使用算法的类之间的耦合度。
代码:
#includeusing namespace std;/* 策略模式*///抽象算法class ConnectDevice{public: virtual void connect() = 0;};//tcp连接class TcpConnect :public ConnectDevice{public: virtual void connect() { cout << "Tcp连接" << endl; }};//RS232连接class RsConnect :public ConnectDevice{public: virtual void connect() { cout << "rs232连接" << endl; }};//串口连接class UartConnect :public ConnectDevice{public: virtual void connect() { cout << "串口连接" << endl; }};//维护具体算法class ContextConnect{public: void ContextConnectFun(ConnectDevice *con) { if (con) { con->connect(); } }};//客户端int main(){ ContextConnect *context = new ContextConnect; if (context) { //由实例化不同的策略,调用不同的算法 ConnectDevice *con = nullptr; con = new TcpConnect(); context->ContextConnectFun(con); con = new RsConnect(); context->ContextConnectFun(con); con = new UartConnect(); context->ContextConnectFun(con); delete context; context = nullptr; if (con) { delete con; con = nullptr; } } return 0;}
转载地址:https://blog.csdn.net/c_shell_python/article/details/107341488 如侵犯您的版权,请留言回复原文章的地址,我们会给您删除此文章,给您带来不便请您谅解!
发表评论
最新留言
关注你微信了!
[***.104.42.241]2024年04月11日 05时52分02秒
关于作者
喝酒易醉,品茶养心,人生如梦,品茶悟道,何以解忧?唯有杜康!
-- 愿君每日到此一游!
推荐文章
【工具篇】10分钟快速上手git与github
2021-06-29
【开发篇】10分钟快速上手spring boot
2021-06-29
【开发篇】10分钟快速spring boot+react前后端分离
2021-06-29
【开发篇】10分钟快速上手spring boot+mybatis增删改查
2021-06-29
【Leetcode刷题篇】leetcode203 移除链表元素
2021-06-29
【Leetcode刷题篇】leetcode108 将有序数组转换为二叉搜索树
2021-06-29
【Leetcode刷题篇】leetcoe109 有序链表转换二叉搜索树
2021-06-29
【Leetcode刷题篇】leetcode938 二叉搜索树的范围和
2021-06-29
【Leetcode刷题篇】leetcode235 二叉搜索树的最近公共祖先
2021-06-29
【Leetcode刷题篇】leetcode236 二叉树的最近公共祖先
2021-06-29
【Leetcode刷题篇】leetcode230 二叉搜索树中第K小的元素
2021-06-29
【Leetcode刷题篇】leetcode173 二叉搜索树迭代器
2021-06-29
【Leetcode刷题篇】leetcode99 恢复二叉搜索树
2021-06-29
【Leetcode刷题篇】leetcode451根据字符出现频率排序
2021-06-29
【Leetcode刷题篇】leetcode703 数据流中的第k大元素
2021-06-29
【Leetcode刷题篇】leetcode378 有序矩阵中第K小的元素
2021-06-29
【Leetcode刷题篇】前K个高频元素
2021-06-29
【Leetcode刷题篇】leetcode373 查找和最小的K对数字
2021-06-29
【Leetcode刷题篇】leetcode367 有效的完全平方数
2021-06-29
【Leetcode刷题篇】剑指offer-数值的整数次方
2021-06-29