Skip to content

커맨드 패턴 (Command pattern)

VG edited this page Dec 19, 2020 · 14 revisions

커맨드 패턴 (Command pattern)

명령 자체를 객체의 형태로 캡슐화하는 패턴


그림출처

예제

만능 버튼C#

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와 형광등을 동시에 끔

    }
}

하나의 버튼으로 여러가지 명령을 수행할 수 있다.

Clone this wiki locally