Design Patterns2011. 12. 13. 23:01

구조 패턴이다. 구현부를 객체를 추상화 함으로서 분리 시킨다.


Abstraction = IMonster
RefinedAbstraction = FireMonster = IceMonster
Implementor = IAttackType
ConcreateImplementorA = FireAttack
ConcreateImplementorB = IceAttack

예제로 보면 새로운 몬스터가 생겨날때 마다 RefinedAbstraction, IAttackType 의 class 가 증가 하게 된다.
몬스터 타입과(IMonster) 공격타입(IAttackType)을 추상화 하였기 때문에, 추후에 몬스터가 추가 된다 하더라도 몬스터를 사용하는 코드에서는 변화가 없고 객체만 늘려주면 된다.

struct IAttackType 
{
	virtual void Attack() = 0; 
};  

struct FireAttack : public IAttackType
{    
	void Attack() { cout << "공격: 불을 뿜다 화이아~" << endl; }; 
};  

struct IceAttack : public IAttackType 
{     
	void Attack() { cout << "공격: 얼음 화살 ㄱㄱ" << endl; }; 
};  	

/////////////   
struct IMonster
{    
	void Attack() 
	{
		attack_type_->Attack();
	}	
	IAttackType* attack_type_;  	
};   

struct FireMonster : public IMonster
{     
	FireMonster() {attack_type_ = new FireAttack;};	
};  

struct IceMonster : public IMonster
{     
	IceMonster() {attack_type_ = new IceAttack;};	
};  
/////////////  	


int _tmain(int argc, _TCHAR* argv[])
{    
	IMonster* fire_monster = new FireMonster;
	IMonster* ice_monster  = new IceMonster;

	fire_monster->Attack();
	ice_monster->Attack();
	
	return 0;
}

공격: 불을 뿜다 화이아~
공격: 얼음 화살 ㄱㄱ

'Design Patterns' 카테고리의 다른 글

POSA1 Layers Architecture pttern  (0) 2013.07.02
Singleton (싱글턴)  (0) 2011.12.06
Prototype  (0) 2011.12.05
Factory Method  (0) 2011.11.16
Builder  (0) 2011.11.15
Posted by 상현달