欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

用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<>();