- 首先声明一个函数式接口,就只接口内只有一个抽象方法
java
//函数式接口
public interface Factory {
Object getObject();
}
- 接口实现类
java
public class SubClass implements Factory {
@Override
public Object getObject() {
return new User();
}
}
- User类
java
public class User {
private String name;
private int age;
public User() {
}
public User(String name, int age) {
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
@Override
public String toString() {
return "User{" +
"name='" + name + '\'' +
", age=" + age +
'}';
}
}
- 测试类:
java
public class LambdaTest {
public static void main(String[] args) {
//1.子类实现接口
Factory factory = new SubClass();
User user = (User)factory.getObject();
System.out.println(user);
//2.匿名内部类
factory = new Factory() {
@Override
public Object getObject() {
return new User("zhangsan",33);
}
};
User object = (User)factory.getObject();
System.out.println(object);
//3.lambda表达式
factory = () -> {
return new User("李斯特",33);
};
Object object1 = factory.getObject();
System.out.println(object1.toString());
System.out.println("-----------------------------------------");
//4.使用lambda表达式,做为参数传递
User user4 = getUserFromFactory(() -> {return new User("wangwuxxx", 223);}, "User");
System.out.println(user4);
System.out.println("-----------------------------------------");
//5. 使用lambda做为返回值
User user5 = (User)getFactory().getObject();
System.out.println(user5);
}
public static User getUserFromFactory(Factory factory,String beanName){
Object obj = factory.getObject();
if(obj != null && obj.getClass().getSimpleName().equals(beanName)){
return (User) obj;
}
return null;
}
public static Factory getFactory(){
return () -> { return new User("dingxx",33); };
}
}