개발/공부
[디자인패턴/C#] 전략 디자인패턴
ssong_dev
2022. 6. 20. 14:40
public class Teacher : MonoBehaviour
{
public string teacherName;
public string subject;
public ILessonStrategy lessonStrategy;
public void SetInfo(ILessonStrategy strategy, string name, string subject)
{
this.lessonStrategy = strategy;
this.teacherName = name;
this.subject = subject;
}
public virtual void Study()
{
Debug.Log(lessonStrategy.Lesson() + subject + "수업");
}
}
//전략을 추가
public interface ILessonStrategy
{
string Lesson();
}
public class KindLessonStrategy : ILessonStrategy
{
public string Lesson()
{
return "친절한";
}
}
public class StrictLessonStrategy : ILessonStrategy
{
public string Lesson()
{
return "엄격한";
}
}
public class TeacherManager : MonoBehaviour
{
private void Start()
{
Teacher teacherA = new Teacher();
teacherA.SetInfo(new KindLessonStrategy(), "선생님", "프로그래밍");
}
}
인터페이스를 통해 전략 클래스를 생성하여 사용하는 디자인 패턴이다.
전략끼리 묶어서 사용할 수 있으므로 개방폐쇄 원칙에 더 잘 맞고
상속 클래스를 계속 늘려나가지 않아도 된다.
보스몬스터 패턴... 등으로 응용 가능하다.