设计模式2——策略模式

工厂模式是针对不同的类型创建不同的对象,当所需要的对象没有变,而只是对它们进行的操作和算法不同时,可使用策略模式。

策略模式创建不同的算法类,并返回一个基类算法对象的指针,并对它进行相关的计算或操作。

 

实例代码

Strategy.h内容

复制代码
 1 #ifndef Strategy_H_H
 2 #define Strategy_H_H
 3 
 4 #include <iostream>
 5 using namespace std;
 6 
 7 class Oper
 8 {
 9 public:
10     Oper() {}
11     virtual int getResult(int a, int b) = 0;
12     virtual ~ Oper() {}
13 };
14 
15 class OperAdd : public Oper
16 {
17 public:
18     virtual int getResult(int a, int b) { return a+b; }
19 };
20 
21 class OperSub : public Oper
22 {
23 public:
24     virtual int getResult(int a, int b) { return a-b; }
25 };
26 
27 class Strategy
28 {
29 public:
30     Strategy(int a0, int b0) : a(a0), b(b0), oper(NULL) {}
31     int getResult(){
32         return oper->getResult(a, b);
33     }
34     void setOper(Oper *oper0){
35         oper = oper0;
36     }
37 private:
38     int a, b;
39     Oper *oper;
40 };
41 
42 void StrategyTest()
43 {
44     Strategy *strategy = new Strategy(4, 3);
45     strategy->setOper( new OperAdd() );
46     cout << strategy->getResult() << endl;
47     strategy->setOper( new OperSub() );
48     cout << strategy->getResult() << endl;
49     delete strategy;
50 }
51 
52 #endif
复制代码

运行结果显而易见。

当然这里并没有考虑内存泄露等问题,使用时需要注意。若需要对其进行优化,可加入引用计数、智能指针等机制。

posted @   丛林小阁楼  阅读(183)  评论(0编辑  收藏  举报
编辑推荐:
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
阅读排行:
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· Docker 太简单,K8s 太复杂?w7panel 让容器管理更轻松!
点击右上角即可分享
微信分享提示