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<Apple> filterApples(List<Apple> inventory, ApplePredicate p){
    List<Apple> result = new ArrayList<Apple>();
    for(Apple apple: inventory){
        if(p.test(apple)){
            result.add(apple);
        }
    }
    return result;
}

// 传递代码
List<Apple> inventory = Arrays.asList(new Apple(80,"green"),
        new Apple(155, "green"),
        new Apple(120, "red"));
List<Apple> heavyApples = filterApples(inventory, new AppleHeavyWeightPredicate());
List<Apple> 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<Apple> 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<Apple> inventory = new ArrayList<Apple>();
    my.prettyPrintApple(inventory, new AppleFancyFormatter());
}

③ 使用匿名类

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

④ 使用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<T>();
    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 来排序

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

// 给sort()函数传递一个匿名类
inventory.sort(new Comparator<Apple>() {
    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<ActionEvent>() {
    public void handle(ActionEvent event) {
        label.setText("Sent!!");
    }
});

// Lambda表达式
button.setOnAction((ActionEvent event) -> label.setText("Sent!!"));
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值