"객체를 생성하는 인터페이스를 정하되 어느 클래스를 인스턴스화 할지는 하위 클래스가 결정하게 하는 패턴 - GoF"
package me.hsnam.factorymethod.base;
/**
* Product
*/
public interface HouseFactory {
default House orderHouse(String name, String email) {
validate(name, email);
House house = createHouse();
prepareFor();
completeMessage(name);
return house;
}
private void validate(String name, String email) {
if (name == null || name.isBlank()) {
throw new IllegalArgumentException("must input name");
}
if (email == null || name.isBlank()) {
throw new IllegalArgumentException("must input email");
}
}
private void prepareFor() {
System.out.println("building house...");
}
House createHouse();
private void completeMessage(String name) {
System.out.println(name + "complete house!");
}
}
package me.hsnam.factorymethod.base;
/**
* ConcreteProduct
*/
public class BlackHouseFactory implements HouseFactory{
@Override
public House createHouse() {
return new BlackHouse();
}
}
package me.hsnam.factorymethod.base;
/**
* ConcreteProduct
*/
public class GreenHouseFactory implements HouseFactory {
@Override
public House createHouse() {
return new GreenHouse();
}
}
package me.hsnam.factorymethod.base;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
@Getter
@Setter
@ToString
public class House {
private String name;
private String color;
private String address;
}
package me.hsnam.factorymethod.base;
/**
* Creator
*/
public class GreenHouse extends House {
public GreenHouse() {
setAddress("갑천면");
setColor("green");
setName("그린하우스");
}
}
package me.hsnam.factorymethod.base;
/**
* Creator
*/
public class BlackHouse extends House{
public BlackHouse() {
setAddress("굴포로");
setColor("black");
setName("블랙하우스");
}
}
package factory;
import me.hsnam.factorymethod.base.BlackHouseFactory;
import me.hsnam.factorymethod.base.GreenHouseFactory;
import me.hsnam.factorymethod.base.House;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
public class FactoryMethod {
@Test
@DisplayName("simple Factory pattern")
public void clientHouseTest() {
System.out.println("Set Order");
House green = new GreenHouseFactory().orderHouse("green", "hsnam@gmail.com");
House black = new BlackHouseFactory().orderHouse("black", "hsnam@gmail.com");
System.out.println(green);
System.out.println(black);
}
}