-
Notifications
You must be signed in to change notification settings - Fork 0
커맨드 패턴 (Command pattern)
VG edited this page Dec 19, 2020
·
14 revisions
명령 자체를 객체의 형태로 캡슐화하는 패턴
Command 인터페이스
public interface Command
{
public void execute();
}
Receiver 클래스
public class Light
{
public void LightOn()
{
Console.WriteLine("형광등을 킴");
}
public void LightOff()
{
Console.WriteLine("형광등을 끔");
}
}
public class TV
{
public void TVOn()
{
Console.WriteLine("TV를 킴");
}
public void TVOff()
{
Console.WriteLine("TV를 끔");
}
}
Concreate 클래스
// 불을 켜는 LightOnCommand 클래스
public class LightOnCommand : Command
{
private Light light;
public LightOnCommand(Light light)
{
this.light = light;
}
// Command 인터페이스의 execute 메서드
public void execute()
{
light.LightOn();
}
}
// 불을 끄는 LightOffCommand 클래스
public class LightOffCommand : Command
{
private Light light;
public LightOffCommand(Light light)
{
this.light = light;
}
// Command 인터페이스의 execute 메서드
public void execute()
{
light.LightOff();
}
}
// TV 켜는 TVOnCommand 클래스
public class TVOnCommand : Command
{
private TV tv;
public TVOnCommand(TV tv)
{
this.tv = tv;
}
// Command 인터페이스의 execute 메서드
public void execute()
{
tv.TVOn();
}
}
// TV 끄는 TVOffCommand 클래스
public class TVOffCommand : Command
{
private TV tv;
public TVOffCommand(TV tv)
{
this.tv = tv;
}
// Command 인터페이스의 execute 메서드
public void execute()
{
tv.TVOff();
}
}
Invoker 클래스
public class Button
{
private Command[] theCommand;
// 버튼의 명령을 theCommand변수에 등록한다.
public void setCommand(Command[] newCommand)
{
this.theCommand = newCommand;
}
// 버튼이 눌리면 현재 등록된 Command의 execute 메서드를 호출한다.
public void pressed()
{
for (int i = 0; i < theCommand.Length; i++)
theCommand[i].execute();
}
}
메인 클래스
class Program
{
static void Main(string[] args)
{
Light light = new Light();
Command lightOnCommand = new LightOnCommand(light);
Command lightOffCommand = new LightOffCommand(light);
TV tv = new TV();
Command tvOnCommand = new TVOnCommand(tv);
Command tvOffCommand = new TVOffCommand(tv);
Button button = new Button();
Command[] commands = new Command[] { lightOnCommand };
button.setCommand(commands); // 커맨드목록 등록
button.pressed(); // 형광등을 킴
commands = new Command[] { tvOnCommand };
button.setCommand(commands); // 커맨드목록 등록
button.pressed(); // TV를 킴
commands = new Command[] { lightOffCommand, tvOffCommand };
button.setCommand(commands); // 커맨드목록 등록
button.pressed(); // TV와 형광등을 동시에 끔
}
}
하나의 버튼으로 여러가지 명령을 수행할 수 있다.
여러 출처를 바탕으로 최대한 오류를 범하지 않도록 작성하였으나, 이 페이지를 작성하는 저 또한 해당 학문을 공부하는 학생입니다.
∴해당 페이지의 정보를 맹신하지 마시길 바랍니다.
-
생성 패턴
-
구조 패턴
- 데코레이터 패턴 (Decorator pattern)
- 어댑터 패턴 (Adapter pattern)
- 퍼사드 패턴 (Facade pattern)
- 프록시 패턴 (Proxy pattern)
- 이터레이터, 컴포지트 패턴 (Iterator, Composite pattern)
-
동작 패턴
- 옵저버 패턴 (Observer pattern)
- 템플릿 메소드 패턴 (Template pattern)
- 커맨드 패턴 (Command pattern)
- 스트래티지 패턴 (Strategy pattern)
- 스테이트 패턴 (State pattern)
-
기타 패턴
- 컴파운드 패턴 (Compound pattern)
- 메소드 체이닝 (Method chaining)
- Dispose 패턴 (Dispose pattern)