zoukankan      html  css  js  c++  java
  • 策略设计模式

    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;
        }
    }
    

    参考资料:

  • 相关阅读:
    MS SQL Server查询优化方法(收藏)
    .net打包并自动安装MS SQL Server数据库<转>
    解决oracle数据库监听器无法启动问题
    SQLServer2008/2005 /2000生成数据字典语句(转载)
    C# 常见错误处理(收藏)
    Oracle数据导入导出
    Oracle Database 9i/10g安装后的基本环境与服务
    Oracle to_char()函数的用法
    oracle参数列表
    SQL Server中存储过程比直接运行SQL语句慢的原因(转载)
  • 原文地址:https://www.cnblogs.com/linkworld/p/7811915.html
Copyright © 2011-2022 走看看