Justin의 개발 로그
public class OriginalFactoryPattern {

    public static Product createProduct(String name) {
        switch(name) {
            case "Car" : return new Car();
            case "Boat" : return new Boat();
            default: throw new RuntimeException("No such product " + name);
        }
    }

    @Test
    void 팩토리메서드_테스트() {
        Product p1 = OriginalFactoryPattern.createProduct("Car");
        Product p2 = OriginalFactoryPattern.createProduct("Boat");
    }

}

 

public class LambdaFactory {
    final static Map<String, Supplier<Product>> map = new HashMap<>();
    static {
        map.put("Car", Car::new);
        map.put("Boat", Boat::new);
    }


    @Test
    void 람다팩토리_테스트() {
        Product p1 = map.get("Car").get();
        Product p2 = map.get("Boat").get();

        Assertions.assertThrows(NullPointerException.class,  () -> {
            Product p3 = map.get("Error").get();
        });
    }
public class LambdaFactory {
    final static Map<String, Supplier<Product>> map = new HashMap<>();
    static {
        map.put("Car", Car::new);
        map.put("Boat", Boat::new);
    }

    public static Product createProduct(String name) {
        Supplier<Product> factory = map.get(name);
        if(factory != null) return factory.get();
        
        throw new IllegalArgumentException("No such product " + name);
    }

    @Test
    void 람다팩토리_테스트2() {
        Product p1 = createProduct("Car");
        Product p2 = createProduct("Boat");

        Assertions.assertThrows(IllegalArgumentException.class,
                () -> {
                        Product p3 = createProduct("Error");
                }
            );
    }
}
profile

Justin의 개발 로그

@라이프노트

포스팅이 좋았다면 "좋아요❤️" 또는 "구독👍🏻" 해주세요!