用lambda简化工厂设计模式
程序员文章站
2024-01-20 16:13:16
...
传统工厂设计模式实现:
import java.util.HashMap;
import java.util.Map;
import java.util.function.Supplier;
public class FactoryPattern {
public final static Map<String, Supplier<Icecream>> iceCreamStation = new HashMap<>();
static {
iceCreamStation.put("choclet", ChocletIceCream::new);
iceCreamStation.put("strawberry", StrawberryIceCream::new);
}
public static void main(String[] args) {
Supplier<Icecream> supplier = iceCreamStation.get("choclet");
if(supplier != null){
Icecream chocletIceCream = supplier.get();
System.out.println(chocletIceCream);
}
}
private static class ChocletIceCream implements Icecream{ }
private static class StrawberryIceCream implements Icecream{}
}
interface Icecream{}
用lambda简化后的工厂模式:
import java.util.HashMap;
import java.util.Map;
import java.util.function.Supplier;
public class FactoryPattern {
public final static Map<String, Supplier<Icecream>> iceCreamStation = new HashMap<>();
static {
iceCreamStation.put("choclet", ChocletIceCream::new);
iceCreamStation.put("strawberry", StrawberryIceCream::new);
}
public static void main(String[] args) {
Supplier<Icecream> supplier = iceCreamStation.get("choclet");
if(supplier != null){
Icecream chocletIceCream = supplier.get();
System.out.println(chocletIceCream);
}
}
private static class ChocletIceCream implements Icecream{ }
private static class StrawberryIceCream implements Icecream{}
}
interface Icecream{}
如果构造器需要参数,看情况重新定义功能接口:
interface TriFunction<T, Y, U, R>{
R apply(T t, Y y, U u);
}
public final static Map<String, TriFunction<String, Integer, Integer, Icecream>> threeParams = new HashMap<>();