전에 한번 정리한 소스를 한번 정리해보는 내용으로...
Marin과 Medic, FIrebet.. 이 3개의 unit가 존재를 하고, 이 unit은 Attack과 Move라는 기본 동작을 갖는다.
Move라는 동작은 모든 Unit이 동일한 동작을 할 수 있지만, Attack 방법은 각기 다르고, 기본적으로 Attack이라는 Method를
갖지만 내부 구현이 다른 동작이 되게 된다.
따라서, 각기 다른 동작을 구현하는 Class를 따로 뽑아내서 구현하는 Strategy Pattern이 사용 가능하다.
먼저, 각기 다른 Attack에 대한 동작을 구현하는 Rifle, Firebazuka, Heal Class를 구현한다.
01.
class
Rifle : IAttack
02.
{
03.
#region IAttack Members
04.
05.
public
string
Attack()
06.
{
07.
return
"dddd..."
;
08.
}
09.
10.
#endregion
11.
}
12.
13.
public
class
Firebazuka : IAttack
14.
{
15.
#region IAttack Members
16.
17.
public
string
Attack()
18.
{
19.
return
"Fire!!..............."
;
20.
}
21.
22.
#endregion
23.
}
24.
25.
public
class
Heal : IAttack
26.
{
27.
#region IAttack Members
28.
29.
public
string
Attack()
30.
{
31.
return
"Heal... "
;
32.
}
33.
34.
#endregion
35.
}
그리고, 이 Attack Method의 IAttack을 인자로 갖는 BaseUnit class를 만들어준다.
BaseUnit은 각 Unit의 parent class가 된다.
01.
class
Runner : IMove
02.
{
03.
#region IMove Members
04.
05.
public
string
MoveTo(
string
direction)
06.
{
07.
return
String.Format(
"To :{0}, Move it!"
, direction);
08.
}
09.
10.
#endregion
11.
}
12.
13.
public
abstract
class
BaseUnit
14.
{
15.
protected
IAttack attackMethod;
16.
protected
IMove moveMethod;
17.
18.
protected
BaseUnit()
19.
{
20.
21.
}
22.
23.
protected
BaseUnit(IAttack attackMethod, IMove moveMethod)
24.
{
25.
this
.attackMethod = attackMethod;
26.
this
.moveMethod = moveMethod;
27.
}
28.
29.
public
virtual
String Attack()
30.
{
31.
return
attackMethod.Attack();
32.
}
33.
34.
public
virtual
String MoveTo(String direction)
35.
{
36.
return
moveMethod.MoveTo(direction);
37.
}
38.
}
이렇게 구성된 BaseUnit을 이용해서 Marin, Firebet, Medic을 구현해준다. 구현된 코드는 다음과 같다.
01.
public
class
Marin : BaseUnit
02.
{
03.
public
Marin() :
base
(
new
Rifle(),
new
Runner())
04.
{
05.
06.
}
07.
}
08.
public
class
Firebet : BaseUnit
09.
{
10.
public
Firebet() :
base
(
new
Firebazuka(),
new
Runner())
11.
{
12.
13.
}
14.
}
15.
public
class
Medic : BaseUnit
16.
{
17.
public
Medic() :
base
(
new
Heal(),
new
Runner())
18.
{
19.
20.
}
21.
}
구현된 Class를 이용해서 Test Code를 작성하면 다음과 같다.
01.
//Marin, Medic, Firebet의 class 생성
02.
BaseUnit unit1 =
new
Marin();
03.
BaseUnit unit2 =
new
Marin();
04.
BaseUnit unit3 =
new
Medic();
05.
BaseUnit unit4 =
new
Firebet();
06.
07.
//BaseUnit으로 Attack, MoveTo를 모두 구현
08.
Console.WriteLine(unit1.Attack());
09.
Console.WriteLine(unit2.Attack());
10.
Console.WriteLine(unit3.Attack());
11.
Console.WriteLine(unit4.Attack());
12.
13.
Console.WriteLine(unit1.MoveTo(
"Direction"
));
14.
Console.WriteLine(unit2.MoveTo(
"Direction"
));
15.
Console.WriteLine(unit3.MoveTo(
"Direction"
));
16.
Console.WriteLine(unit4.MoveTo(
"Direction"
));
Strategy Pattern은 같은 Interface에서 각각 다른 동작을 하는 class들을 구현하는 방법으로,
Method의 주체가 되는 Rifle, Firebazuk, Heal class의 구성이 관건이다. 다른 것을 객체화하라. 라는
Design pattern의 성경같은 구절이 생각난다.