팩토리 패턴에 가장 큰 장점은 앞으로 어떤 클래스가 추가될지 모르는 상태에서 팩토리 클래스에서 if만 추가하면 객체가 생성되고, 서브클래스만 구현하면 된다는 것이다. 얼마나 획기적인가...


예제를 통해 알아보자.

package AbstactFactory;


public abstract class Ethnic {

public void Create() {

}

}

package AbstactFactory;


public class EthnicFactory {

public String _ethnic;

public EthnicFactory(String _ethnic){

this._ethnic = _ethnic;

}

public Ethnic getInstance(){

if(_ethnic.equals("Human")){

return new Human();

}

else{

return new Elf();

}

}

}

package AbstactFactory;


public class Character extends Human {

private String ethnicName;

private Ethnic _ethnic;

public Character(){

this("Human");

}

public Character(String ethnicName){

this.ethnicName = ethnicName;

this.Create();

}

public void Create(){

EthnicFactory factory = new EthnicFactory(ethnicName);

Ethnic ethnic = factory.getInstance();

ethnic.Create();

_ethnic = ethnic;

}

}

package AbstactFactory;

public class Human extends Ethnic{
private String ethnicName;
public Human(){
ethnicName = "Human";
}
@Override
public void Create() {
// TODO Auto-generated method stub
super.Create();
System.out.println(ethnicName + " created.");
}
}


메인 구현 부분


Character Human = new Character("Human");
Character Elf = new Character("Elf");


'시스템분석 및 설계 > 디자인패턴' 카테고리의 다른 글

MVC 모델 정리  (0) 2009.08.21

+ Recent posts