《过滤器模式(极简c++)》

本文章属于专栏- 概述 - 《设计模式(极简c++版)》-CSDN博客


本章简要说明过滤器模式。本文分为**++模式说明、本质思想、实践建议、代码示例++**四个部分。

模式说明

方案: 过滤器模式是一种结构型设计模式,用于过滤一组对象,基于特定条件筛选出所需的对象。

优点:

  1. 松耦合性: 过滤器模式将过滤条件与具体操作解耦,使得条件的变化不影响其他部分。
  2. 可组合性: 可以轻松地组合多个过滤器以实现复杂的过滤逻辑。

缺点:

  1. 类数量增加: 可能会引入过多的具体过滤器类,增加代码复杂度。
本质思想:过滤器模式的本质思想是将过滤条件封装到对象中,然后使用这些对象对原始数据进行过滤,以获取符合条件的结果集。
实践建议:在过滤器很多时。定义一个通用的过滤器接口,以便不同类型的过滤器都可以实现该接口。在需要经过多层过滤时,多个过滤器组合在一起形成过滤链,以实现复杂的过滤需求。这样过滤逻辑集中在一个类中,更方便管理和维护。

示例代码:

cpp 复制代码
#include <iostream>
#include <vector>

// 基类 Bird
class Bird {
public:
    virtual bool filter() const = 0;
    virtual ~Bird() {}
};

// 具体类:鸟类
class Sparrow : public Bird {
public:
    bool filter() const override { return true; } // 飞行鸟
};

class Penguin : public Bird {
public:
    bool filter() const override { return false; } // 水中鸟
};

// 具体过滤器:飞行鸟过滤器
class FlyingBirdFilter {
public:
    bool filter(const Bird& bird) const {
        return bird.filter();
    }
};

// 过滤器使用示例
int main() {
    std::vector<Bird*> birds = {new Sparrow(), new Penguin()};
    FlyingBirdFilter flyingFilter;

    for (Bird* bird : birds) {
        if (flyingFilter.filter(*bird)) {
            std::cout << "This bird can fly." << std::endl;
        }else {
            std::cout << "This bird can't fly." << std::endl;
        }
    }

    for (Bird* bird : birds) {
        delete bird;
    }

/*
输出:
    This bird can fly.
    This bird can't fly.
*/

    return 0;
}
相关推荐
C^h3 小时前
c++ string
开发语言·c++
raindayinrain4 小时前
c++高性能--原子操作,无锁编程,操作顺序
开发语言·c++·性能优化
学逆向的4 小时前
C++ 合并命名空间
开发语言·c++·网络安全
Zhao-Jichao4 小时前
VS2026 打包 C++ 程序生成 EXE,借助 Installer Project 扩展工具
开发语言·c++
小徐不徐说5 小时前
C++ 接口与插件设计:从工厂注册到 Qt 动态插件
数据库·c++·qt·系统架构·程序设计
大都督会赢的5 小时前
C++第一节课
开发语言·c++
UIU1145 小时前
P1233 [ICPC 2001 Taejon R] 木棍加工
数据结构·c++·算法·动态规划
TMedical6 小时前
MedPlanning 截骨模拟矫形功能
c++·图像处理·人工智能·qt·健康医疗
qq_406981036 小时前
共享变量一 关于extern与const
开发语言·c++
chari克里8 小时前
QT5.15.2 + msvc2022部署全流程说明(windows可联网环境)
开发语言·c++·qt