過濾器模式

2021-08-18 10:54:27 字數 2051 閱讀 1114

簡介:這種模式允許開發人員使用不同的標準來過濾一組物件,通過邏輯運算以解耦的方式把它們連線起來。

這種型別的設計模式屬於結構型模式,它結合多個標準來獲得單一標準。

在本例中,以水果作為過濾的物件。水果的顏色和口味各有差別。有時我們只需要酸味的水果,有時只需要黃色的水果,這種情況下,就需要用到過濾器模式,根據一定的標準進行篩選。

/**

*建立乙個水果類,屬性包括名稱,口味和顏色

*/public class fruit

public void setname(string name)

public string gettaste()

public void settaste(string taste)

public string getcolor()

public void setcolor(string color)

public fruit(string name, string taste, string color)

@override

public string tostring() }

/** *定義乙個介面,過濾的標準

*/inte***ce criterion

/** *過濾紅色的水果

*/class redcri implements criterion

}return fruits; }}

/** *過濾黃色的水果

*/class yellowcri implements criterion

}return fruits; }}

/** *過濾甜味的水果

*/class sweetcri implements criterion

}return fruits; }}

/** *過濾酸味的水果

*/class sourcri implements criterion

}return fruits; }}

/** * 「與」條件,同時需要滿足兩個篩選條件。

*/class addcri implements criterion

@override

public listchoosecri(listlist)

}/**

*或條件,只要滿足其中乙個條件即可

*/class orcri implements criterion

@override

public listchoosecri(listlist)

} return fruits2;

}}

主方法:

public class main 

}

執行結果:

所有的甜味水果[fruit [name=香蕉, taste=sweet, color=yellow], fruit [name=梨, taste=sweet, color=yellow], fruit [name=蘋果, taste=sweet, color=red], fruit [name=西瓜, taste=sweet, color=red], fruit [name=哈密瓜, taste=sweet, color=yellow]]

紅色甜味的水果[fruit [name=蘋果, taste=sweet, color=red], fruit [name=西瓜, taste=sweet, color=red]]

紅色或者甜味的水果[fruit [name=香蕉, taste=sweet, color=yellow], fruit [name=梨, taste=sweet, color=yellow], fruit [name=蘋果, taste=sweet, color=red], fruit [name=西瓜, taste=sweet, color=red], fruit [name=哈密瓜, taste=sweet, color=yellow], fruit [name=西紅柿, taste=sour, color=red], fruit [name=櫻桃, taste=sour, color=red]]

過濾器模式

過濾器模式 用於過濾篩選 1.定義常規類 2.定義抽象介面類,用於過濾的函式接收list,並返回list 3.定義具體過濾類實現抽象介面,重寫過濾用的函式 4.定義用於操作的具體過濾類實現抽象介面,add,or,not 5.客戶端使用抽象介面類,進行具體的過濾操作 1.定義常規類 class dog...

過濾器模式

網上對過濾器的解釋已經很多了,而且這個模式的概念理解起來不算很難,但是發現網上提供的demo 寫得不好,所以這裡就給大家介紹一下如何實現合理的過濾器模式。這樣我們應該怎麼做呢?需要解耦,就需要把比較函式提取出來。經過思考,我們可以讓過濾器類持有乙個委託,這個委託就是用來過濾資料的,我們在建構函式中給...

過濾器模式

定義 過濾器模式 intercepting filter pattern 又稱標準模式 criteria pattern 主要用於統一接收並過濾客戶端的請求,根據過濾器的選擇,將請求傳送給對應的目標處理程式。過濾器模式屬於物件結構型模式。要點主要角色 目標物件 target 處理請求,根據要求執行任...