Fork me on GitHub

策略设计模式

public class TestLambda{
    List<Employee> employees = Arrays.aslist(
            new Employee("张三",16,1000);
            new Employee("李四",22,2000);
            new Employee("熊大",25,1300);
            new Employee("熊二",32,1200);
            new Employee("赵六",43,3200);
    );

    @Test
    public void test2(){
        List<Employee> list = filterEmpByAge(employees);

        for(Employee emp : list){
            System.out.println(emp);
        }
    }

    // 需求一: 获取当前公司中,员工年龄大于等于30的员工信息
    public List<Employee> filterEmpByAge(List<Employee> list){
        List<Employee> emps = new ArrayList<>();

        for(Employee emp : list){
            if(emp.getAge() >= 30){
                emps.add(emp);
            }
        }
        return emps;
    }

    // 需求二: 获取当前公司中,员工工资大于等于2000的员工信息
    public List<Employee> filterEmpBySal(List<Employee> list){
        List<Employee> emps = new ArrayList<>();

        for(Employee emp : list){
            if(emp.getSalary() >= 2000){
                emps.add(emp);
            }
        }
        return emps;
    }

    // 优化方式一: 策略设计模式
    @Test
    public void test3(){
        // 按年龄过滤
        List<Employee> list = filterEmployee(employees,new FilterEmployeeByAge());

        for(Employee employee : list){
            System.out.println(employee);
        }

        // 按工资过滤
        List<Employee> list2 = filterEmployee(employees,new FilterEmployeeBySal());

        for(Employee employee : list2){
            System.out.println(employee);
        }
    }


    public List<Employee> filterEmployee(List<Employee> list, MyPredicte<Employee> mp){
        List<Employee> emps = new ArrayList<>();

        for(Employee employee : list){
            if(mp.test(employee)){
                emps.add(employee);
            }
        }
    }
}

// 创建泛型接口
public interface MyPredicate<T>{
    public boolean test(T t);
}

// 创建泛型接口的实现类
public class filterEmpByAge implements MyPredicate<Employee> {

    public boolean test(Employee emp){
        return emp.getAge() >= 30;
    }
}

public class filterEmpBySal implements MyPredicate<Employee> {

    public boolean test(Employee emp){
        return emp.getSalary() >= 2000;
    }
}

参考资料:

posted @ 2017-11-09 22:59  小a的软件思考  阅读(137)  评论(0编辑  收藏  举报