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");
}
);
}
}
'프로그래밍 > OOP_Pattern_TDD' 카테고리의 다른 글
자바 DSL - 중첩된 함수(NestedFunction) 패턴 (0) | 2023.03.08 |
---|---|
자바 DSL - 메서드 체인 패턴 (0) | 2023.03.08 |
람다 - 의무체인 패턴 (0) | 2023.03.03 |
람다 - 옵저버 패턴 (0) | 2023.03.03 |
람다로 효과적 프로그래밍 - 템플릿메서드 패턴 (0) | 2023.03.02 |