Java_通过行为参数化传递代码

通过行为参数化传递代码
把一个行为(一段代码)封装起来,并通过传递和使用创建的行为(例如对Apple的不同谓词)将方法的行为参数化。

// 定义Apple类
public class Apple{
    private Integer weight = null;
    private String color = null;
    public Apple(Integer weight, String color){
        this.weight = weight;
        this.color = color;
    }
    public Integer getWeight(){
        return this.weight;
    }
    public String getColor(){
        return this.color;
    }
}

① 将筛选条件抽象化,作为参数进行传递

// 定义一个接口来对选择标准建模
public interface ApplePredicate{
    boolean test (Apple apple);
}

// 用ApplePredicate的多个实现代表不同的选择标准
public class AppleHeavyWeightPredicate implements ApplePredicate{
    public boolean test(Apple apple){
        return apple.getWeight() > 150;
    }
}

public class AppleGreenColorPredicate implements ApplePredicate{
    public boolean test(Apple apple){
        return "green".equals(apple.getColor());
    }
}

public class AppleRedAndHeavyPredicate implements ApplePredicate{
    public boolean test(Apple apple){
        return "red".equals(apple.getColor())
                && apple.getWeight() > 150;
    }
}

// 根据抽象条件筛选
public static List filterApples(List inventory, ApplePredicate p){
    List result = new ArrayList();
    for(Apple apple: inventory){
        if(p.test(apple)){
            result.add(apple);
        }
    }
    return result;
}

// 传递代码
List inventory = Arrays.asList(new Apple(80,"green"),
        new Apple(155, "green"),
        new Apple(120, "red"));
List heavyApples = filterApples(inventory, new AppleHeavyWeightPredicate());
List greenApples = filterApples(inventory, new AppleGreenColorPredicate());

② 将输出信息抽象化,作为参数传递

// 定义一个接口来对输出信息建模
public interface AppleFormatter{
    String accept (Apple apple);
}

public class AppleFancyFormatter implements AppleFormatter{
    public String accept(Apple apple){
        String characteristic = apple.getWeight() > 150 ? "heavy" : "light";
        return "A " + characteristic + " " + apple.getColor() +" apple";
    }
}

public class AppleSimpleFormatter implements AppleFormatter{
    public String accept(Apple apple){
        return "An apple of " + apple.getWeight() + "g";
    }
}

public static void prettyPrintApple(List inventory, AppleFormatter formatter){
    for(Apple apple: inventory){
        String output = formatter.accept(apple);
        System.out.println(output);
    }
}

public void main(String[] args){
    __1__ my = new __1__();
    List inventory = new ArrayList();
    my.prettyPrintApple(inventory, new AppleFancyFormatter());
}

③ 使用匿名类

List redApples = filterApples(inventory, new ApplePredicate() {
    public boolean test(Apple apple){
        return "red".equals(apple.getColor());
    }
});

④ 使用Lambda表达式

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

⑤ 将List类型抽象化

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

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

List redApples = filter(inventory, (Apple apple) -> "red".equals(apple.getColor()));
List evenNumbers = filter(numbers, (Integer i) -> i % 2 == 0);

⑥ 例子:用Comparator 来排序

// java.util.Comparator
public interface Comparator {
    public int compare(T o1, T o2);
}

// 给sort()函数传递一个匿名类
inventory.sort(new Comparator() {
    public int compare(Apple a1, Apple a2){
        return a1.getWeight().compareTo(a2.getWeight());
    }
 });

// 给sort()函数传入一个Lambda表达式
inventory.sort( (Apple a1, Apple a2) -> a1.getWeight().compareTo(a2.getWeight()));

⑦ 例子:用Runnable 执行代码块

// java.lang.Runnable
public interface Runnable{
    public void run();
}

// 使用这个接口创建执行不同行为的线程
Thread t = new Thread(new Runnable() {
    public void run(){
        System.out.println("Hello world");
     }
 });

// 用Lambda表达式的话,看起来是这样
Thread t = new Thread(() -> System.out.println("Hello world"));

⑧ 例子:GUI 事件处理

Button button = new Button("Send");

button.setOnAction(new EventHandler() {
    public void handle(ActionEvent event) {
        label.setText("Sent!!");
    }
});

// Lambda表达式
button.setOnAction((ActionEvent event) -> label.setText("Sent!!"));

你可能感兴趣的:(Java)