行为参数化
什么是行为参数化
个人理解:把行为抽象出来进行封装,让代码适应需求的变化,并把行为或代码作为参数传递,并且遵循一些设计原则。
这让我想起了一个设计模式:策略模式(封装算法族,动态改变算法使用者无感知)
interface Action {
}
class ActionA implements Action {
}
class ActionB implements Action {
}
JAVA8中行为参数化
一个方法接受多个不同的行为作为参数,并在内部使用他们,完成不同行为的能力
实例:
假如你是金融公司的程序员,根据条件筛选出一些客户,筛选维度:逾期数、逾期金额、年龄、性别等
客户贷后资料实体:
public class Customer {
private int overduePeriod;
private double amount;
private int gender;
private int age;
public Customer() {
}
public Customer(int overduePeriod, double amount, int gender, int age) {
super();
this.overduePeriod = overduePeriod;
this.amount = amount;
this.gender = gender;
this.age = age;
}
public int getOverduePeriod() {
return overduePeriod;
}
public void setOverduePeriod(int overduePeriod) {
this.overduePeriod = overduePeriod;
}
public double getAmount() {
return amount;
}
public void setAmount(double amount) {
this.amount = amount;
}
public int getGender() {
return gender;
}
public void setGender(int gender) {
this.gender = gender;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
谓词:
public interface Predicat<T> {
boolean judge(T t);
}
过滤:
import java.util.ArrayList;
import java.util.List;
public class Filter {
private static List<Customer> customers = new ArrayList<>();
public static void main(String[] args) {
// 初始化list
init();
// 匿名类的方式
List<Customer> list = filter(customers, new Predicat<Customer>() {
@Override
public boolean judge(Customer c) {
// 逾期数大于12期同时金额必须大于10000
return c.getOverduePeriod() >= 12 && c.getAmount() > 10000;
}
});
System.out.println("客户数:" + list.size() + " " + list);
// lambda
List<Customer> list2 = filter(customers, (Customer c) -> c.getOverduePeriod() >= 12 && c.getAmount() > 10000);
System.out.println("客户数:" + list2.size() + " " + list2);
}
public static void init() {
for (int i = 0; i < 100; i++) {
Customer c = new Customer((int) (Math.random() * 100), Math.random() * (i + 1) * 100000, i % 2, (int)(Math.random() * 100));
customers.add(c);
}
}
public static <T> List<T> filter(List<T> list, Predicat<T> p) {
List<T> result = new ArrayList<>();
for (T t : list) {
if (p.judge(t)) {
result.add(t);
}
}
return result;
}
}
java8既然支持lambda,就最好不要用匿名类的方式:
一、匿名类笨重占用空间
二、匿名类可读性差
网友评论