생성(Creational) 패턴
구체적인 클래스에 의존하지 않고 서로 연관되거나 의존적인 객체들의 조합을 만드는 인터페이스를 제공하는 패턴
부품 조달을 위한 Factory가 필요한데 현재 S사와 K사가 있다고 하자.
MotorFactory.class
public class MotorFactory{
public static Motor createMotor(String vendorID) {
Motor motor = null;
switch (vendorID) {
case "S":
motor = new S_Motor();
break;
case "K":
motor = new K_Motor();
break;
}
return motor;
}
}
DoorFactory.class
public class DoorFactory {
public static Door createDoor(String vendorID) {
Door door = null;
switch (vendorID) {
case "S":
door = new S_Door();
break;
case "K":
door = new K_Door();
break;
}
return door;
}
}
Main.class
public class Main {
public static void main(String[] args) {
Door S_Door = DoorFactory.createDoor("S");
Motor S_Motor = MotorFactory.createMotor("S");
S_Door.open();
S_Motor.move();
}
}
S_Door Open
S_Motor Move
Factory.class
public abstract class Factory {
abstract Motor createMotor();
abstract Door createDoor();
}
S_Factory.class
public class S_Factory extends Factory{
@Override
Motor createMotor() { return new S_Motor(); }
@Override
Door createDoor() { return new S_Door(); }
}
K_Factory.class
public class K_Factory extends Factory {
@Override
Motor createMotor() { return new K_Motor(); }
@Override
Door createDoor() { return new K_Door(); }
}
Main.class
public class Main {
public static void main(String[] args) {
Factory factory = new S_Factory();
Motor motor = factory.createMotor();
Door door = factory.createDoor();
door.open();
motor.move();
}
}
S_Door Open
S_Motor Move
참조: