官网:https://www.runoob.com/design-pattern/design-pattern-tutorial.html
主要解决:在有多种算法相似的情况下,使用 if...else 所带来的复杂和难以维护。
何时使用:一个系统有许多许多类,而区分它们的只是他们直接的行为。
关键代码:实现同一个接口。(动态代理也是实现同一个接口)
- demo演示:
要求:1. 查询工资>5000,的员工;
2.查询年龄>30,的员工
接口定义,由子类实现自己具体的行为
public interface MyPredicate<T> {
boolean doEmployees(T t);
}
public class myTest {
//测试数据
List<Employee> employees = Arrays.asList(
new Employee("张三", 18, 3333.33),
new Employee("李四", 25, 5000.33),
new Employee("王五", 32, 6000.33),
new Employee("赵六", 55, 90000.00),
new Employee("孙七", 17, 7777.00)
);
/**
* 定义要调用的方法,抽取出公共行为,由子类来扩展不同的实现方式
*/
public <T> List<T> executeStrategy(List<T> list, MyPredicate<T> myPredicate) {
List<T> tList = new ArrayList<>();
for (T t : list) {
if (myPredicate.doEmployees(t)) {
tList.add(t);
}
}
return tList;
}
//测试方法调用executeStrategy ,由lambda表达式实现子类行为
@Test
public void testStrategy5() {
List<Employee> employees = executeStrategy(this.employees, (e) -> {
return e.getAge() > 30;
});
employees.forEach(System.out::println);
}
@Test
public void testStrategy6() {
executeStrategy(this.employees, (e) -> e.getSalary() > 5000);
employees.forEach(System.out::println);
}
}