5

前端设计模式——过滤器模式 - 1800000000nm

 1 year ago
source link: https://www.cnblogs.com/ronaldo9ph/p/17235262.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

前端设计模式——过滤器模式

前端设计模式中的过滤器模式(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' 的商品,最后打印出符合条件的商品列表。


Recommend

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK