2018-2-13-PHP设计模式【过滤器模式】

layouttitledateauthordescin_head
post
PHP设计模式之过滤器模式
2018-02-13 20:00:02 +0800
南丞
设计模式(Design Pattern)是一套被反复使用、多数人知晓的、经过分类编目的、代码设计经验的总结。使用设计模式是为了可重用代码、让代码更容易被他人理解、保证代码可靠性。设计模式于己于他人于系统都是多赢的;设计模式使代码编制真正工程化;设计模式是软件工程的基石脉络,如同大厦的结构一样。
<style> .article-content p{ text-indent: 2em; line-height: 1.75rem; }</style>

过滤器模式

<?php

use pf\arr\PFarr;

header('Content-type:text/html;charset-utf-8');
require_once './vendor/autoload.php';
//对一系列结构相同的对象,定义特定的规则,进行筛选和过滤。

/**
 * 接口 - 过滤器
 */
interface Filter
{
    public function Go($person);// 过滤方法 - 参数是一个存储了对象的数组
}

/**
 * 具体化  过滤器 按性别过滤对象
 */
class Gender implements Filter
{
    private $_gender; //过滤条件

    public function __construct($gender)
    {
        $this->_gender = $gender;
    }

    public function Go($person)
    {
        $personsFilter = [];
        foreach ($person as $k => $v) {
            if ($v->gender === $this->_gender) {
                $personsFilter[] = $person[$k];
            }
        }
        return $personsFilter;
    }
}

/**
 * 具体化 - 过滤器 - 按运动类型过滤对象
 */
class SportType implements Filter
{
    private $_sportType; // 过滤条件

    public function __construct($sportType)
    {
        $this->_sportType = $sportType;
    }

    # 实现过滤方法
    public function Go($person)
    {
        $personsFilter = [];
        foreach ($person as $k => $v) {
            if ($v->sportType === $this->_sportType) {
                $personsFilter[] = $person[$k];
            }
        }
        return $personsFilter;
    }
}

/**
 * 运动类
 */
class Motion
{
    public $gender;
    public $sportType;
    public function __construct($gender,$sportType)
    {
        $this->gender    = $gender;
        $this->sportType = $sportType;
    }
}
# 定义一组对象列表
$persons = array();
$persons[] = new Motion('男', '篮球');
$persons[] = new Motion('女', '游泳');
$persons[] = new Motion('男', '羽毛球');
$persons[] = new Motion('女', '篮球');
$persons[] = new Motion('男', '游泳');
$persons[] = new Motion('女', '羽毛球');

# 按过滤男性
$filterGender = new Gender('男');
PFarr::dd($filterGender->Go($persons));

# 过滤运动项目篮球
$filterSportType = new SportType('游泳');
PFarr::dd($filterSportType->Go($persons));
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值