팩토리 메서드 디자인패턴
- 객체를 생성하기 위해 인터페이스를 정의하지만, 어떤 클래스의 인스턴스를 생성할 지에 대한 결정은 서브클래스가 내리도록 한다. 가상 생성자라고도 불린다.
클래스 설명
어떤 클래스가 자신이 생성해야 하는 객체의 클래스를 예측할 수 없을 때,
생성할 객체를 기술하는 책임을 자신의 서브클래스가 지정했으면 할 때,
객체 생성의 책임을 몇 개의 보조 서브클래스 가운데 하나에게 위임하고, 어떤 서브클래스가 위임자인지에 대한 정보를 국소화 시키고 싶을 때, 팩토리 메서드를 사용한다.
클래스 사용방법
var factory1: ConcreteFactory = new ConcreteFactory();
var product1: Product = factory1.buyProduct("camera");
product1.getName(); //카메라 출력
var factory2: ConcreteFactory = new ConcreteFactory ();
var product2: Product = factory2.buyProduct("smartphone");
product2.getName() //스마트폰
클래스 구성
//Product : 팩토리 메서드가 생성하는 객체 인터페이스 정의
package
{
public class Product
{
protected var _name: String = "";//서브클래스에서 이름 정의
public function getName( name: String )
{
return _name;
}
}
}
//ConcreteProduct : Product 클래스에 정의된 인터페이스를 실제 구현.
package
{
public class Camera extends Product
{
public function Camera()
{
_name = "카메라";
}
}
}
//Creator : Product 타입의 객체를 반환하는 팩토리 메서드 선언.
package
{
public class Factory
{
public function Factory()
{
throw new Error( "Not exist Abstract Class" );
}
//doCreateProduct 메서드( 팩토리메서드 )
public function doCreateProduct( p: Name ): Product
{
throw new Error( "This is a Abstract Method" );
}
public function buyProduct( type: String ): Product
{
var product: Product = doCreateProduct( type );
//중간공정 생략...
return product;
}
}
}
ConcreteFactory : 팩토리 메서드를 재정의
package
{
public class ConcreteFactory
{
public function ConcreteFactory()
{
}
override public function doCreateProduct( p: Name ): Product
{
var item: Product = null;
switch( p )
{
case "camera":
item = new Camera();
break;
case "smartphone":
item = new SmartPhone();
break;
case "computer":
item = new Computer();
break;
}
return item;
}
}
}
'디자인 패턴' 카테고리의 다른 글
디자인패턴 : Template Method (0) | 2011.08.03 |
---|---|
디자인패턴 : Facade (0) | 2011.08.03 |
디자인패턴 : Adapter (0) | 2011.08.03 |
디자인패턴 : Decorator (0) | 2011.08.03 |
디자인패턴 : Proxy (0) | 2011.08.03 |