前端設計模式中的過濾器模式(Filter Pattern)是一種結構型設計模式,它允許我們使用不同的條件來過濾一組物件,并回傳符合條件的物件串列,
在過濾器模式中,我們有一個包含多個物件的串列,需要根據一些條件來篩選出符合條件的物件,通常情況下,可以使用多個過濾器來實作這個功能,每個過濾器都是一個獨立的類,它實作了一個過濾條件,我們可以將這些過濾器組合在一起,來實作復雜的過濾操作,
在實際開發中,可以使用過濾器模式來實作諸如搜索、過濾、排序等功能,例如,在一個商品串列頁面中,我們可以使用過濾器模式來根據價格、品牌、型別等條件來篩選出用戶感興趣的商品,
以下是一個簡單的 JavaScript 示例代碼,演示了如何使用過濾器模式來篩選陣列中的元素:
class Filter { constructor(criteria) { this.criteria = criteria; } meetCriteria(elements) { return elements.filter(element => this.criteria(element)); } } class PriceFilter extends Filter { constructor(price) { super(element => element.price <= price); } } class BrandFilter extends Filter { constructor(brand) { super(element => element.brand === brand); } } const products = [ { name: 'Product A', price: 10, brand: 'Brand A' }, { name: 'Product B', price: 20, brand: 'Brand B' }, { name: 'Product C', price: 30, brand: 'Brand C' }, ]; const priceFilter = new PriceFilter(20); const brandFilter = new BrandFilter('Brand A'); const filteredProducts = priceFilter.meetCriteria(products); const finalProducts = brandFilter.meetCriteria(filteredProducts); console.log(finalProducts); // Output: [{ name: 'Product A', price: 10, brand: 'Brand A' }]
在上面的示例代碼中,我們定義了一個 `Filter` 類作為過濾器模式的基類,然后我們定義了兩個子類 `PriceFilter` 和 `BrandFilter`,它們分別根據價格和品牌來過濾商品,我們還定義了一個商品陣列 `products`,然后使用這兩個過濾器來篩選出價格低于等于 20 并且品牌為 'Brand A' 的商品,最后列印出符合條件的商品串列,
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/547532.html
標籤:JavaScript
