《过滤器模式(极简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;
}
相关推荐
wangluoqi5 小时前
c++ 逆元 小总结
开发语言·c++
瓦特what?5 小时前
插 入 排 序
开发语言·c++
『往事』&白驹过隙;5 小时前
C/C++中的格式化输出与输入snprintf&sscanf
linux·c语言·c++·笔记·学习·iot·系统调用
Je1lyfish5 小时前
CMU15-445 (2026 Spring) Project#1 - Buffer Pool Manager
linux·数据库·c++·后端·链表·课程设计·数据库架构
zyeyeye5 小时前
自定义类型:结构体
c语言·开发语言·数据结构·c++·算法
俩娃妈教编程6 小时前
2023 年 03 月 二级真题(1)--画三角形
c++·算法·双层循环
航哥的女人6 小时前
C++文件操作
开发语言·c++
L_Aria7 小时前
3824. 【NOIP2014模拟9.9】渴
c++·算法·图论
ShineWinsu7 小时前
对于模拟实现C++list类的详细解析—上
开发语言·数据结构·c++·算法·面试·stl·list
Mr YiRan7 小时前
C++语言类中各个重要函数原理
java·开发语言·c++