PHP设计模式-过滤器 发表于 2017-03-29 | 分类于 PHP | 评论数: | 阅读次数: 本文字数: 2.9k | 阅读时长 ≈ 3 分钟 适用性 允许我们使用不同的规则过滤某一组对象 代码示例123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153/** * 过滤接口 */interface FilterInterface{ /** * 过滤方法 * * @param SportsMan $person 运动员 * @return mixed */ public function filter(array $person);}/** * 按运动项目过滤实体 */class SportsPerson{ /** * 性别 * @var string */ private $_gender = ''; /** * 按照本运动项目过滤 * @var string */ private $_sportType = ''; /** * 构造函数 * @param string $gender * @param string $sportType */ public function __construct($gender='', $sportType='') { $this->_gender = $gender; $this->_sportType = $sportType; } /** * 魔法函数 * @param string $value * @return mixed */ public function __get($value='') { $value = '_' . $value; return $this->$value; }}/** * 按性别过滤实体 */class FilterGender implements FilterInterface{ /** * 按照本性别过滤 * @var string */ private $_gender = ''; /** * 构造函数 * @param string $gender */ public function __construct($gender='') { $this->_gender = $gender; } /** * 过滤方法 * * @param array $persons 运动员集合 * @return mixed */ public function filter(array $persons) { foreach ($persons as $k => $v) { if ($v->gender === $this->_gender) { $personsFilter[] = $persons[$k]; } } return $personsFilter; }}/** * 按运动项目过滤实体 */class FilterSportType implements FilterInterface{ /** * 按照本运动项目过滤 * @var string */ private $_sportType = ''; /** * 构造函数 * @param string $sportType */ public function __construct($sportType='') { $this->_sportType = $sportType; } /** * 过滤方法 * * @param array $persons 运动员集合 * @return mixed */ public function filter(array $persons) { foreach ($persons as $k => $v) { if ($v->sportType === $this->_sportType) { $personsFilter[] = $persons[$k]; } } return $personsFilter; }}try { // 定义一组运动员 $persons = []; echo '<pre/>'; $persons[] = new SportsPerson('male', 'basketball'); $persons[] = new SportsPerson('female', 'basketball'); $persons[] = new SportsPerson('male', 'football'); $persons[] = new SportsPerson('female', 'football'); $persons[] = new SportsPerson('male', 'swim'); $persons[] = new SportsPerson('female', 'swim'); // 按过滤男性 $filterGender = new FilterGender('male'); var_dump($filterGender->filter($persons)); // 过滤运动项目篮球 $filterSportType = new FilterSportType('basketball'); var_dump($filterSportType->filter($persons));} catch (\Exception $e) { echo $e->getMessage();}