【設計模式】過濾器模式

過濾器顧名思義,定義一些過濾規則,將符合要求的內容篩選,就比如過濾不同大小或者不同顏色的水果,需要顏色和大小過濾器,篩選條件獨立為對象,可以通過靈活組合形成過濾鏈條。避免大量使用判斷語句。

案例代碼:篩選不同顏色的蘋果

  1. 被過濾對象(蘋果)
// 蘋果對象
class Apple {private String color;private int weight;public Apple(String color, int weight) {this.color = color;this.weight = weight;}public String getColor() { return color; }public int getWeight() { return weight; }
}
  1. 過濾器接口
// 過濾器接口
interface Filter {List<Apple> filter(List<Apple> apples);
}
  1. 具體過濾器實現
// 顏色過濾器(篩選紅色蘋果)
class ColorFilter implements Filter {public List<Apple> filter(List<Apple> apples) {List<Apple> result = new ArrayList<>();for (Apple apple : apples) {if ("red".equalsIgnoreCase(apple.getColor())) {result.add(apple);}}return result;}
}// 重量過濾器(篩選重量大于150g的蘋果)
class WeightFilter implements Filter {public List<Apple> filter(List<Apple> apples) {List<Apple> result = new ArrayList<>();for (Apple apple : apples) {if (apple.getWeight() > 150) {result.add(apple);}}return result;}
}
  1. 組合過濾器(多條件篩選)
// 組合過濾器(同時滿足多個條件)
class AndFilter implements Filter {private Filter filter1;private Filter filter2;public AndFilter(Filter filter1, Filter filter2) {this.filter1 = filter1;this.filter2 = filter2;}public List<Apple> filter(List<Apple> apples) {List<Apple> temp = filter1.filter(apples);return filter2.filter(temp);}
}
  1. 使用過濾器模式
public class FilterDemo {public static void main(String[] args) {List<Apple> apples = Arrays.asList(new Apple("Red", 200),new Apple("Green", 160),new Apple("Red", 140));// 單條件篩選:紅色蘋果Filter colorFilter = new ColorFilter();List<Apple> redApples = colorFilter.filter(apples);System.out.println("紅色蘋果數量:" + redApples.size()); // 輸出:2// 組合篩選:紅色且重量>150gFilter weightFilter = new WeightFilter();Filter andFilter = new AndFilter(colorFilter, weightFilter);List<Apple> result = andFilter.filter(apples);System.out.println("符合條件的蘋果數量:" + result.size()); // 輸出:1}
}

應用場景案例:用戶權限過濾
場景描述
篩選出同時滿足以下條件的用戶:

  • 年齡在18歲以上
  • 所在城市為“北京”
  • 注冊時間在2023年以后
    代碼實現
// 用戶對象
class User {private String name;private int age;private String city;private LocalDate registerDate;public User(String name, int age, String city, LocalDate registerDate) {this.name = name;this.age = age;this.city = city;this.registerDate = registerDate;}// Getter方法省略...
}// 年齡過濾器
class AgeFilter implements Filter {private int minAge;public AgeFilter(int minAge) {this.minAge = minAge;}public List<User> filter(List<User> users) {List<User> result = new ArrayList<>();for (User user : users) {if (user.getAge() >= minAge) {result.add(user);}}return result;}
}// 城市過濾器
class CityFilter implements Filter {private String city;public CityFilter(String city) {this.city = city;}public List<User> filter(List<User> users) {List<User> result = new ArrayList<>();for (User user : users) {if (city.equalsIgnoreCase(user.getCity())) {result.add(user);}}return result;}
}// 注冊時間過濾器
class DateFilter implements Filter {private LocalDate startDate;public DateFilter(LocalDate startDate) {this.startDate = startDate;}public List<User> filter(List<User> users) {List<User> result = new ArrayList<>();for (User user : users) {if (user.getRegisterDate().isAfter(startDate)) {result.add(user);}}return result;}
}// 使用示例
public class UserFilterDemo {public static void main(String[] args) {List<User> users = Arrays.asList(new User("張三", 25, "北京", LocalDate.of(2024, 1, 1)),new User("李四", 17, "上海", LocalDate.of(2024, 2, 1)),new User("王五", 30, "北京", LocalDate.of(2022, 5, 1)));// 創建過濾器Filter ageFilter = new AgeFilter(18);Filter cityFilter = new CityFilter("北京");Filter dateFilter = new DateFilter(LocalDate.of(2023, 1, 1));// 組合過濾:年齡>=18 && 城市=北京 && 注冊時間>2023Filter combinedFilter = new AndFilter(ageFilter, new AndFilter(cityFilter, dateFilter));List<User> validUsers = combinedFilter.filter(users);System.out.println("有效用戶數量:" + validUsers.size()); // 輸出:1}
}

過濾器模式應用場景

  1. 數據篩選:
    • 電商商品篩選(價格、品牌、評分)
    • 日志過濾(錯誤級別、時間范圍)
  2. 權限系統:
    • 用戶角色過濾(管理員、VIP用戶)
    • 數據權限過濾(部門、區域)
  3. 數據清洗:
    • 去除無效數據(空值、異常值)
    • 敏感信息過濾(手機號脫敏)

過濾器模式優勢

  1. 靈活組合條件:通過組合多個過濾器實現復雜邏輯
  2. 解耦過濾邏輯:每個過濾器獨立維護,新增條件無需修改已有代碼
  3. 可復用性高:同一過濾器可用于不同場景(如“北京用戶篩選”可用于報表和推送)

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/diannao/76363.shtml
繁體地址,請注明出處:http://hk.pswp.cn/diannao/76363.shtml
英文地址,請注明出處:http://en.pswp.cn/diannao/76363.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

STM32 CAN學習(一)

CAN總線應用最多的是汽車領域。 CAN&#xff08;Controller Area Network&#xff09;控制器 局域 網 局域網&#xff1a;把幾臺電腦連接到一臺路由器上&#xff0c;這幾臺電腦就可以進行通訊了。 控制器在汽車中的專業術語叫做ECU&#xff08;Electronic Control Unit&…

多線程開發中List的使用

由于ArrayList在多線程高并發情況下是不安全的&#xff0c;因此要慎用&#xff0c;那么此時如果涉及到集合操作&#xff0c;應該怎么選&#xff1a; 方案一&#xff1a;Vector: 特點&#xff1a;通過給所有方法都用 synchronized 修飾從而保證線程安全&#xff0c; 缺點&…

論文閱讀筆記:Denoising Diffusion Implicit Models (2)

0、快速訪問 論文閱讀筆記&#xff1a;Denoising Diffusion Implicit Models &#xff08;1&#xff09; 論文閱讀筆記&#xff1a;Denoising Diffusion Implicit Models &#xff08;2&#xff09; 論文閱讀筆記&#xff1a;Denoising Diffusion Implicit Models &#xff08…

人工智能在醫療領域的前沿應用與挑戰

在當今數字化時代&#xff0c;人工智能&#xff08;AI&#xff09;技術正以前所未有的速度改變著我們的生活&#xff0c;其中醫療領域無疑是受益最為顯著的行業之一。從疾病診斷、治療方案制定到患者護理&#xff0c;AI的應用不僅提高了醫療服務的效率和質量&#xff0c;還為醫…

【計算機網絡】HTTP與HTTPS

文章目錄 1. HTTP定義2. HTTP交互3. HTTP報文格式3.1 抓包工具-fiddler3.2 抓包操作3.3 報文格式3.3.1 請求報文3.3.2 響應報文 4. URL5. 請求頭中的方法6. GET和POST的區別7. HTTP報頭7.1 Host7.2 Content_Length7.3 Content_Type7.4 User-Agent(UA)7.5 Referer7.6 Cookie 8 狀…

怎樣提升大語言模型(LLM)回答準確率

怎樣提升大語言模型(LLM)回答準確率 目錄 怎樣提升大語言模型(LLM)回答準確率激勵與規范類知識關聯類情感與語境類逆向思維類:為什么不,反面案例群體智慧類明確指令類示例引導類思維引導類約束限制類反饋交互類:對話激勵與規范類 給予獎勵暗示:在提示詞中暗示模型如果回…

【分享】內外網文件擺渡系統:讓數據傳輸更安全更可靠

【分享】Ftrans內外網文件擺渡系統&#xff1a;讓數據傳輸更安全更可靠&#xff01; 隨著大數據時代的到來&#xff0c;數據的重要性日漸得到重視&#xff0c;數據作為數字經濟時代下的基礎性資源和戰略性資源&#xff0c;是決定國家經濟發展水平和競爭力的核心驅動力。以行業…

Python自動化面試通關秘籍

Python自動化測試工程師面試&#xff0c;不僅僅是考察你的代碼能力&#xff0c;更看重你如何在項目中靈活運用工具和框架解決實際問題。如果你正準備面試&#xff0c;這篇文章將為你總結最常見的高頻考題及答題技巧&#xff0c;幫助你快速上手&#xff0c;通關面試&#xff0c;…

Logstash開啟定時任務增量同步mysql數據到es的時區問題

本文使用修改時間modify_date作為增量同步檢測字段&#xff0c;可檢測新增和修改&#xff0c;檢測不到刪除&#xff0c;檢測刪除請使用canal查詢binlog日志同步數據 檢測修改時間字段為varchar的時候可以先創建索引&#xff0c;并設置對應的mapping為&#xff08;可以無視時區…

如何使用 FastAPI 構建 MCP 服務器

哎呀&#xff0c;各位算法界的小伙伴們&#xff01;今天咱們要聊聊一個超酷的話題——MCP 協議&#xff01;你可能已經聽說了&#xff0c;Anthropic 推出了這個新玩意兒&#xff0c;目的是讓 AI 代理和你的應用程序之間的對話變得更順暢、更清晰。不過別擔心&#xff0c;為你的…

【Git】-- 處理 Git 提交到錯誤分支的問題

如果你不小心把本應提交到 test 分支的代碼提交到了 master 分支&#xff08;但尚未 push&#xff09;&#xff0c;可以按照以下步驟解決&#xff1a; 方法一&#xff08;推薦&#xff09;&#xff1a;使用 git reset 和 git stash 首先&#xff0c;確保你在 master 分支&…

通用目標檢測技術選型分析報告--截止2025年4月

前言 本文撰寫了一份關于通用目標檢測&#xff08;General Object Detection&#xff09;的技術選型分析報告&#xff0c;覆蓋2000至2025年技術演進歷程&#xff0c;重點納入YOLO-World、RT-DETR、Grounding DINO等2024-2025年的最新模型。 報告將包括技術定義、行業現狀、技…

鏈路追蹤Skywalking

一、什么是Skywalking 分布式鏈路追蹤的一種方式&#xff1a;Spring Cloud SleuthZipKin&#xff0c;這種方案目前也是有很多企業在用&#xff0c;但是作為程序員要的追逐一些新奇的技術&#xff0c;Skywalking作為后起之秀也是值得大家去學習的。 Skywalking是一個優秀的國產…

websocket獲取客服端真實ip

在websocket建立連接時,獲取訪問客戶端的真實ip 1. websocket建立連接過程 2. pom依賴 <dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-websocket</artifactId></dependency>3. 添加配置,握…

NSSCTF(MISC)—[justCTF 2020]pdf

相應的做題地址&#xff1a;https://www.nssctf.cn/problem/920 binwalk分離 解壓文件2AE59A.zip mutool 得到一張圖片 B5F31內容 B5FFD內容 轉換成圖片 justCTF{BytesAreNotRealWakeUpSheeple}

部分國產服務器CPU及內存性能測試情況

近日對部分國產服務器進行了CPU和內存的性能測試&#xff0c; 服務器包括華錕振宇、新華三和中興三家&#xff0c;CPU包括鯤鵬、海光和Intel&#xff0c;初步測試結果如下&#xff1a; 服務器廠商四川華錕振宇新華三中興中興服務器HuaKun TG225 B1R4930 G5R5930 G2R5300 G4操作…

【無標題】Scala函數基礎

函數和方法的區別 1&#xff09; 核心概念 &#xff08;1&#xff09; 為完成某一功能的程序語句的集合&#xff0c;稱為函數。 &#xff08;2&#xff09; 類中的函數稱之方法。 2&#xff09; 案例實操 &#xff08;1&#xff09; Scala 語言可以在任何的語法結構中聲明…

uniapp -- 列表垂直方向拖拽drag組件

背景 需要在小程序中實現拖拽排序功能,所以就用到了m-drag拖拽組件,在開發的過程中,發現該組件在特殊的場景下會有些問題,并對其進行了拓展。 效果 組件代碼 <template><!-- 創建一個垂直滾動視圖,類名為m-drag --><scroll

conda安裝python 遇到 pip is configured with locations that require TLS/SSL問題本質解決方案

以前寫了一篇文章&#xff0c;不過不是專門為了解決這個問題的&#xff0c;但是不能訪問pip install 不能安裝來自https 協議的包問題幾乎每次都出現&#xff0c;之前解決方案只是治標不治本 https://blog.csdn.net/wangsenling/article/details/130194456???????https…

【初階數據結構】隊列

文章目錄 目錄 一、概念與結構 二、隊列的實現 隊列的定義 1.初始化 2.入隊列 3.判斷隊列是否為空 4.出隊列 5.取隊頭數據 6.取隊尾數據 7.隊列有效個數 8.銷毀隊列 三.完整源碼 總結 一、概念與結構 概念&#xff1a;只允許在一端進行插入數據操作&#xff0c;在另一端進行刪除…