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

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


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

模式说明

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

优点:

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

缺点:

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

示例代码

#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;
}

  • 10
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值