[자바 디자인패턴 소스코드] Command Pattern

커맨드패턴

/**
 * 디자인패턴 - 커맨드패턴
 * 실행될 기능을 캡슐화함으로써 기능의 실행을 요구하는 호출자(invoker) 클래스와
 * 실제 기능을 실행하는 수신자(receiver) 클래스 사시의 의종성을 제거한다.
 * 따라서 실행될 기능의 변경에도 클래스를 수정 없이 그대로 사용할 수 있도록 해준다.
 */
public class CommandPattern {
    public static void main(String[] args) {
        Zillot zillot = new Zillot();
        ZillotCommand zillotCommand = new ZillotCommand(zillot);

        Protoss protoss1 = new Protoss(zillotCommand);
        protoss1.make();

        Nexus nexus = new Nexus();
        NexusCommand nexusCommand = new NexusCommand(nexus);

        Protoss protoss2 = new Protoss(nexusCommand);
        protoss2.make();

        protoss2.setCommand(zillotCommand);
        protoss2.make();
    }
}

interface  Command {
    public abstract void execute();
}

class Protoss {
    private Command command;

    public Protoss(Command command) {
        setCommand(command);
    }

    public void setCommand(Command command) {
        this.command = command;
    }

    public void make() {
        command.execute();
    }
}

class Zillot {
    public void create() {
        System.out.println("creating zillot.");
    }
}

class ZillotCommand implements Command {
    private Zillot zillot;

    public ZillotCommand(Zillot zillot) {
        this.zillot = zillot;
    }

    public void execute() {
        this.zillot.create();
    }
}

class Nexus {
    public void build() {
        System.out.println("building Nexus.");
    }
}

class NexusCommand implements Command {
    private Nexus nexus;

    public NexusCommand(Nexus nexus) {
        this.nexus = nexus;
    }

    public void execute() {
        this.nexus.build();
    }
}

 

이 글을 공유하기

댓글

Designed by JB FACTORY