Files
Hui-s-notebook/通过行为参数化传递代码.md
2023-09-10 10:50:53 +08:00

1.8 KiB
Raw Blame History

处理频繁变更的需求的一种开发模式

应对不断变化的需求

筛选绿苹果-> 把颜色作为参数-> 把你能想到的每个属性做筛选

行为参数化

定义一个接口

public interface ApplePredicate{
	boolean test(Apple apple);
}

通过ApplePredicate多个实现代表不同选择标准

AppleHeavyWeightPredicateAppleGreenColorPredicate

根据抽象条件筛选

多种行为,一个参数

可以重复使用一个方法,给它不同的行为来达到不同目的

对付啰嗦

匿名类

button.setOnAction(new EventHandler<ActionEvent>() {
	public void handle(ActionEvent event) {
		System.out.println("Woooo a click! ! ");
	}
});

缺点:

  1. 很笨重,占用很多空间
  2. 用起来令人费解

使用Lambda表达式

List<Apple> result =
            filterApples(inventory, (Apple apple) -> "red".equals(apple.getColor()));

将List类型抽象化

public interface Predicate<T>{
	boolean test(T t);
}

public static <T> List<T> filter(List<T> list, Predicate<T> p) {
	List<T> result = new ArrayList<>();
	for (T e: list){
		if(p.test(e)) {
			result.add(e);
		}
	}
	return result;
}

List<Apple> redApples = filter(inventory, (Apple apple)-> "red".equals(apple.getColor()));


List<Integer> evenNumbers = filter(numbers, (Integer i)-> i % 2==0);

真实的例子

用Comparator排序

inventory.sort(
              (Apple a1, Apple a2)-> a1.getWeight().compareTo(a2.getWeight()));

用Runnable执行代码块

线程就像是轻量级进程:它们自己执行一个代码块。 可以使用Runnable接口表示一个要执行的代码块返回Void

Thread t=new Thread(()-> System.out.println("Hello world"));

GUI事件处理

hread t=new Thread(()-> System.out.println("Hello world"));