Use FunctionalInterface provide factory methods

1.

First, provide the User class

public class User {
    
    private int id;
    private String name;
    
    public User(int id, String name) {
    this.id = id;
    this.name = name;
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

}

UserFactory create a User factory class, is a function interface

import java.util.ArrayList;
import java.util.List;

public class ConstrMethodRef {
    
    @FunctionalInterface
    interface UserFactory<U extends User>{
    U create(int id, String name);
    }
    
    static UserFactory<User> uf = User::new;
    
    public static void main(String[] args) {

    List<User> users = new ArrayList<User>();
    for(int i=0; i<10; i++) {
        users.add(uf.create(i, "billy" + Integer.toString(i)));
    }
    users.stream().map(User::getName).forEach(System.out::println);
    
     
    }

}

After you create UserFactory instance, a call to UserFactory.create (), the constructor will be entrusted to an actual User will be to create a User object instance.

Guess you like

Origin www.cnblogs.com/luffystory/p/11963689.html