전략 패턴 간단한 예제
Class 구현부
namespace StrategyPattern
{
class Context
{
private IStrategy IStrategy;
public Context() { }
public Context(IStrategy strategy)
{
IStrategy = strategy;
}
public void SetValue(IStrategy strategy)
{
IStrategy = strategy;
}
public void DoSomething()
{
Console.WriteLine("context DoSomething()");
var test = IStrategy.algo(1);
}
}
public interface IStrategy
{
object algo(int data);
}
class Someobj1 : IStrategy
{
public object algo(int data)
{
Console.WriteLine($"this is someobj1 : {data}");
return new object();
}
}
class Someobj2 : IStrategy
{
public object algo(int data)
{
Console.WriteLine($"this is someobj2 : {data}");
return new object();
}
}
}
Main
namespace StrategyPattern;
public class MainProject
{
static void Main(string[] args)
{
var context = new Context();
context.SetValue(new Someobj1());
context.DoSomething();
context.SetValue(new Someobj2());
context.DoSomething();
}
}
결과
context DoSomething()
this is someobj1 : 1
context DoSomething()
this is someobj2 : 1
또다른 예제
using System;
using System.Collections.Generic;
namespace StrategyPatternExample
{
// 무기 클래스
public class Weapon
{
private List<IElementalStrategy> elementalStrategies = new List<IElementalStrategy>();
public void AddElementalStrategy(IElementalStrategy elementalStrategy)
{
elementalStrategies.Add(elementalStrategy);
}
public void Attack()
{
if (elementalStrategies.Count == 0)
{
Console.WriteLine("Attacking with a standard weapon.");
}
else
{
Console.Write("Attacking with a weapon that has the following elements: ");
foreach (var strategy in elementalStrategies)
{
Console.Write(strategy.GetElementalType() + " ");
}
Console.WriteLine();
}
}
}
// 속성 전략 인터페이스
public interface IElementalStrategy
{
string GetElementalType();
}
// 물속성 전략
public class WaterElementalStrategy : IElementalStrategy
{
public string GetElementalType()
{
return "Water";
}
}
// 독속성 전략
public class PoisonElementalStrategy : IElementalStrategy
{
public string GetElementalType()
{
return "Poison";
}
}
// 불속성 전략
public class FireElementalStrategy : IElementalStrategy
{
public string GetElementalType()
{
return "Fire";
}
}
// 흙속성 전략
public class EarthElementalStrategy : IElementalStrategy
{
public string GetElementalType()
{
return "Earth";
}
}
class Program
{
static void Main(string[] args)
{
var weapon = new Weapon();
// 두 개 이상의 속성을 가진 무기를 만듭니다.
weapon.AddElementalStrategy(new WaterElementalStrategy());
weapon.AddElementalStrategy(new FireElementalStrategy());
weapon.Attack();
// 세 개의 속성을 가진 무기로 변경합니다.
weapon.AddElementalStrategy(new EarthElementalStrategy());
weapon.Attack();
}
}
}
'프로그래밍' 카테고리의 다른 글
[레거시 코드 활용 전략] ch13. 변경해야 하는데, 어떤 테스트를 작성해야 할지 모르겠다 (0) | 2024.01.09 |
---|---|
[VisualStudio] 고정 탭 옵션 (2) | 2024.01.04 |
[레거시 코드 활용 전략] ch12. 클래스 의존 관계, 반드시 없애야할까? (1) | 2024.01.02 |
[TDD] 테스트 대역 (Test double) (0) | 2023.12.13 |
정규 표현식 변환 시 유용한 사이트 (0) | 2023.11.17 |