过滤器模式(Filter Pattern)/标准模式(Criteria Pattern)
过滤器模式(Filter Pattern)或标准模式(Criteria Pattern)是一种设计模式,这种模式允许开发人员使用不同的标准来过滤一组对象,通过逻辑运算以解耦的方式把它们连接起来。这种类型的设计模式属于结构型模式,它结合多个标准来获得单一标准。
这是对符合条件的对象进行过滤,不是简单的对传递的参数进行判断。
示例代码:
<?php
class User{
private $gender='male';
private $age=0;
function __construct($gender,$age){
$this->gender=$gender;
$this->age=$age;
}
function __get($attr){
return $this->$attr;
}
}
interface Criteria{
public function meet($users);
}
class MaleCriteria implements Criteria{
public function meet($users){
$tmp_arr=[];
foreach ($users as $user) {
if($user->gender=='male'){
$tmp_arr[]=$user;
}
}
return $tmp_arr;
}
}
class FemaleCriteria implements Criteria{
public function meet($users){
$tmp_arr=[];
foreach ($users as $user) {
if($user->gender=='female'){
$tmp_arr[]=$user;
}
}
return $tmp_arr;
}
}
class AgeCriteria implements Criteria{
public function meet($users){
$tmp_arr=[];
foreach ($users as $user) {
if($user->age>28){
$tmp_arr[]=$user;
}
}
return $tmp_arr;
}
}
class AndCriteria{
private $one_criteria;
private $the_other_criteria;
public function __construct($one_criteria,$the_other_criteria){
$this->one_criteria=$one_criteria;
$this->the_other_criteria=$the_other_criteria;
}
public function meet($users){
return $this->the_other_criteria->meet($this->one_criteria->meet($users));
}
}
class OrCriteria{
private $one_criteria;
private $the_other_criteria;
public function __construct($one_criteria,$the_other_criteria){
$this->one_criteria=$one_criteria;
$this->the_other_criteria=$the_other_criteria;
}
public function meet($users){
$users_one=$this->one_criteria->meet($users);
$users_the_other=$this->the_other_criteria->meet($users);
foreach ($users_the_other as $key=>$user_2) {
$diff_found_key=-1;
foreach ($users_one as $user_1){
if($user_2==$user_1){
$diff_found_key=$key;
}
}
if(-1==$diff_found_key){
$users_one[]=$user_2;
}
}
return $users_one;
}
}
function main(){
$users[]=new User('male',35);
$users[]=new User('female',23);
$users[]=new User('male',28);
$users[]=new User('female',29);
$users[]=new User('male',27);
$mc=new MaleCriteria();
$fc=new FemaleCriteria();
$ac=new AgeCriteria();
$and_c=new AndCriteria($ac, $fc); //女性而且年龄大于28
print_r($and_c->meet($users));
$or_c=new OrCriteria($ac, $fc); //女性或者是年龄大于28
print_r($or_c->meet($users));
}main();
运行结果:
Array
(
[0] => User Object
(
[gender:User:private] => female
[age:User:private] => 29
)
)
Array
(
[0] => User Object
(
[gender:User:private] => male
[age:User:private] => 35
)
[1] => User Object
(
[gender:User:private] => female
[age:User:private] => 29
)
[2] => User Object
(
[gender:User:private] => female
[age:User:private] => 23
)
)