全站年SVIP
全站1000+试题无限查看
interface Filter { public function doFilter(); } class RegularFilter implements Filter { public function doFilter() { echo '业务处理'; } } class FilterChain { private $filters = []; public function addFilter(Filter $filter) { $this->filters[] = $filter; } public function doFilter() { foreach ($this->filters as $filter) { $filter->doFilter(); } } } class FilterManager { public $filterChain; public function __construct() { $this->filterChain = new FilterChain(); } public function addFilter(Filter $filter) { $this->filterChain->addFilter($filter); } public function doFilter() { $this->filterChain->doFilter(); } } $filterManager = new FilterManager(); $filter = new RegularFilter(); $filterManager->addFilter($filter); $filterManager->doFilter();
实际应用场景
Servlet Filter。
SpringMVC Interceptor。
拦截器和过滤器的区别
过滤器 (Filter) : 过滤数据。请求过滤参数。 拦截器 (Interceptor) : 拦截请求。拦截请求并且做相关的处理。 登陆拦截器,未登陆会跳转到登陆页面。
PHP自己实现一个拦截过滤器
结构中包含的角色
最小可表达代码
interface Filter { public function doFilter(); } class RegularFilter implements Filter { public function doFilter() { echo '业务处理'; } } class FilterChain { private $filters = []; public function addFilter(Filter $filter) { $this->filters[] = $filter; } public function doFilter() { foreach ($this->filters as $filter) { $filter->doFilter(); } } } class FilterManager { public $filterChain; public function __construct() { $this->filterChain = new FilterChain(); } public function addFilter(Filter $filter) { $this->filterChain->addFilter($filter); } public function doFilter() { $this->filterChain->doFilter(); } } $filterManager = new FilterManager(); $filter = new RegularFilter(); $filterManager->addFilter($filter); $filterManager->doFilter();
实际应用场景
Servlet Filter。
SpringMVC Interceptor。
拦截器和过滤器的区别
过滤器 (Filter) : 过滤数据。请求过滤参数。 拦截器 (Interceptor) : 拦截请求。拦截请求并且做相关的处理。 登陆拦截器,未登陆会跳转到登陆页面。