设为首页 加入收藏

TOP

反馈法学习设计模式(一)——策略模式Strategy Pattern(二)
2019-09-02 23:54:04 】 浏览:43
Tags:反馈 学习 设计模式 策略 模式 Strategy Pattern
package Demo.filter;

//
// 该方法为最基本的过滤器
// 用于抽象各个过滤器中的循环, 遍历, 收集等重复行为
// 采用接口的默认方法实现
//
// Created by auhnayuil on 17-9-24.
//
public interface Filter<T> {

    default Collection<T> collect(Collection<T> targets, Predicate<T> predicate) {
        Class<? extends Collection> clazz = targets.getClass();
        Collection result = null;
        try {
             //该部分代码块, 通过反射生成集合的实例对象. 得到一个空的结果集对象
             result = clazz.newInstance();
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }

        for(T target : targets){
            //循环遍历目标集合, 并且通过接口形成策略判断是否符合过滤器条件
            //收集符合条件的结果
            if(predicate.test(target))
                result.add(target);
        }
        return result;
    }
}
package Demo.predicate;

//
// 策略设计模式(Staregy)
// 定义了一系列的算法族, 并将其封装, 可以相互替换且在运行时选择所需要的合适的"策略"
// Created by auhnayuil on 17-9-24.
//
public class AppleRedAndWeightPrdicate implements Predicate<Apple> {

    @Override
    public boolean test(Apple target) {
        return ("red".equals(target.getColor())
                && target.getWeight() > 0.0F);
    }
}

参考链接

[Java8实战] https://book.douban.com/subject/26772632/
[Baidu] https://baike.baidu.com/item/%E7%AD%96%E7%95%A5%E6%A8%A1%E5%BC%8F/646307?fr=aladdin
[菜鸟教程] http://www.runoob.com/design-pattern/strategy-pattern.html

首页 上一页 1 2 下一页 尾页 2/2/2
】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
上一篇java设计模式-工厂模式(springwe.. 下一篇装饰器模式

最新文章

热门文章

Hot 文章

Python

C 语言

C++基础

大数据基础

linux编程基础

C/C++面试题目