공부/C#
[C#] 디자인패턴 - 싱글톤, Factory, state(상태 패턴)
굴러다니다니
2023. 3. 28. 17:37
Singleton: 객체 인스턴스가 1개, 정적, 시스템에 많이 적용
Factory: 양산(미니언 같이)
State: 상태에 따라 무언가를 호출, 한정된 상태 안에서 계속(유한상태머신 FSM) → 몬스터 AI에 많이 사용, 상태이상에 사용
Program.cs
class test
{
public test()
{
Console.WriteLine("test");
}
public void Call()
{
Console.WriteLine("일반클래스");
}
} //main 전에 선언
//... main문 시작
test testing = new test();
testing.Call();
//singleton singleton = new singleton(); 싱글톤 선언을 해 두었기에 아래 식으로 바로 접근이 가능하다
singleton.Instance.singleton_call();
Console.WriteLine(singleton.Instance.get_int());
Console.WriteLine(singleton.Instance.a);
singleton.cs
class singleton
{
//싱글톤의 기본 형태
private static singleton _instance = null;
public static singleton Instance //본인 자체를 객체화
{
get
{
if(_instance == null)
{
_instance = new singleton();
}
return _instance;
}
}
public int a = 5;
//private int b = 6;
//다른 클래스에서 접근 불가
public singleton()
{
Console.WriteLine("지금 생성");
}
public void singleton_call()
{
Console.WriteLine("singleton_call()");
}
public int get_int()
{
return a;
}
}
state.cs
public enum state
{
Happy,
Angry,
Sad
}
public interface Istate
{
void Action();
}
public class Happy : Istate
{
//상태에 클래스를 만들어 상태를 객체화시킴
//상태 패턴은 상태를 객체화함으로 상태가 행동을 할 수 있도록 위임하는 패턴
string name;
public Happy(string name)
{
this.name = name;
}
public void Action()
{
Console.WriteLine($"{name}은 행복");
}
}
public class Angry : Istate
{
string name;
public Angry(string name)
{
this.name = name;
}
public void Action()
{
Console.WriteLine($"{name}은 분노");
}
}
public class Sad : Istate
{
string name;
public Sad(string name)
{
this.name = name;
}
public void Action()
{
Console.WriteLine($"{name}은 슬픔");
}
}
public class Human
{
public string name;
public Dictionary<state, Istate> State_dictionary;
public Human(string name)
{
this.name = name;
State_dictionary = new Dictionary<state, Istate>();
State_dictionary.Add(state.Happy, new Happy(name));
State_dictionary.Add(state.Angry, new Angry(name));
State_dictionary.Add(state.Sad, new Sad(name));
}
}
Program.cs main문
Human person = new Human("이름");
Console.WriteLine($"{person.name}");
person.State_dictionary[state.Happy].Action();
person.State_dictionary[state.Angry].Action();
person.State_dictionary[state.Sad].Action();
728x90
반응형