객체를 만들어 반환하는 함수를 (생성자 대신) 제공하여 초기화 과정을 외부에서 보지 못하게 숨기고 반환 타입을 제어하는 방법.
즉 공장을 만들어서 객체를 만드는 일을 위임한다.
아래 예는 스위치,버튼,드랍박스를 행위에 따라 객체 생성하는 기능이다.
public abstract class Component {
protected abstract String getCompName();
public Component() {
System.out.println(this.getCompName()+" 실행");
}
}
class Button extends Component {
@Override
protected String getCompName() {
return "버튼";
}
}
class Switch extends Component {
@Override
protected String getCompName() {
return "스위치";
}
}
class DropBox extends Component {
@Override
protected String getCompName() {
return "드랍박스";
}
}
public class Factory {
public Component doComponet(Usage u) {
if(u==Usage.PRESS) {
return new Button();
} else if(u==Usage.TOGGLE) {
return new Switch();
} else {
return new DropBox();
}
}
}
public class Console {
private Factory factory = new Factory();
private Component _button;
private Component _switch;
private Component _dropbox;
// 팩토리 사용하지 않는 메서드
void withoutFactory() {
_button = new Button();
_switch = new Switch();
_dropbox = new DropBox();
}
// 팩도리 사용 메서드
void withFactory() {
_button = factory.doComponet(Usage.PRESS);
_switch = factory.doComponet(Usage.TOGGLE);
_dropbox = factory.doComponet(Usage.EXPAND);
}
}
public class MyProgram {
public static void main(String[] args) {
Console console = new Console();
console.withFactory();
console.withoutFactory();
}
}
버튼 실행
스위치 실행
드랍박스 실행
버튼 실행
스위치 실행
드랍박스 실행
팩토리는 객체를 생성하는데 공정 과정이 비밀인 말 그대로 공장이다.