策略模式主要是应对需求变化导致方法小规模重复改动,由于方法只有小部分不一致,大部分是一样的,重复定义就显得代码冗余,这时就需要使用策略模式,定义一个接口,策略方法中调用的是接口中的方法,而具体执行时需要使用方传递具体实现,从而避免了重复方法的定义,如下为过滤员工中年龄,姓名的需求:
public class Strategy { private List<Employee> employees=Arrays.asList(new Employee[]{ new Employee("tom", 18), new Employee("jerry", 19), new Employee("jack", 20), new Employee("rose", 21) }); /** * 策略方法 */ public List<Employee> filterEmployee(List<Employee> list,CompareByWhere<Employee> where) { List<Employee> res=new ArrayList<Employee>(); for (Employee employee : list) { if(where.filter(employee))//策略接口中方法,具体实现需要使用者根据需求决定 { res.add(employee); } } return res; } @Test public void func() { List<Employee> filterEmployees = filterEmployee(employees,new CompareByWhere<Employee>(){ @Override public boolean filter(Employee t) {//把过滤条件交由具体需求,而不需要修改策略方法 //return t.getAge()>=20; //需求1:年龄大于等于20岁的 return t.getName().contains("j");//需求2:姓名包含j的 } }); for (Employee employee : filterEmployees) { System.out.println(employee); } } } /** *策略接口 */ interface CompareByWhere<T>{ boolean filter(T t); } class Employee{ private String name; private int age; public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } @Override public String toString() { return "Employee [name=" + name + ", age=" + age + "]"; } public Employee() { super(); } public Employee(String name, int age) { super(); this.name = name; this.age = age; } public void setAge(int age) { this.age = age; } }