명령을 객체화하여 실행 취소, 재실행 기능 제공하는 디자인 패턴

Command Pattern은 객체 지향 디자인 패턴 중 하나로, 명령을 객체화하여 실행 취소, 재실행 등의 기능을 제공하는 방식입니다. 이 패턴은 객체를 실행하는 것이 아니라 객체를 생성하여 실행을 위임합니다. 이는 명령 실행과 관련된 모든 세부사항을 캡슐화하고, 이를 나중에 재사용하거나 수정할 수 있도록 합니다.

Command Pattern은 매우 유용한 디자인 패턴으로, 많은 개발자들이 사용합니다. 이 패턴을 활용하면 유지보수성을 증가시키고 개발속도를 향상시킬 수 있습니다. 이 글에서는 Command Pattern의 장점들과 이를 활용하는 방법을 알아보겠습니다.

유지보수성 증가와 개발속도 향상, Command Pattern의 장점들

Command Pattern의 가장 큰 장점은 유지보수성을 증가시키는 것입니다. 이 패턴을 사용하면 명령 실행과 관련된 모든 코드를 하나의 객체에 캡슐화하게 되므로, 코드 수정이나 유지보수 작업이 필요할 때 매우 용이해집니다. 또한 이 패턴을 사용하면 새로운 명령을 추가하거나 삭제하는 것도 매우 쉬워집니다.

또한 Command Pattern은 개발속도를 향상시키는데도 큰 역할을 합니다. 이 패턴을 사용하면 코드 작성이 매우 간단해집니다. 명령을 객체화하면 코드가 더욱 모듈화되어 개발자가 작성하는 코드 양이 줄어들게 됩니다. 이는 개발 시간을 단축시키고 빠른 프로토타이핑을 가능하게 합니다.

아래는 Command Pattern을 활용한 예제 코드입니다.

interface Command {
    void execute();
}

class LightOnCommand implements Command {
    private Light light;

    public LightOnCommand(Light light) {
        this.light = light;
    }

    @Override
    public void execute() {
        light.on();
    }
}

class LightOffCommand implements Command {
    private Light light;

    public LightOffCommand(Light light) {
        this.light = light;
    }

    @Override
    public void execute() {
        light.off();
    }
}

class Light {
    void on() {
        System.out.println("Light is on");
    }

    void off() {
        System.out.println("Light is off");
    }
}

class RemoteControl {
    private Command command;

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

    void pressButton() {
        command.execute();
    }
}

public class Main {
    public static void main(String[] args) {
        Light light = new Light();
        Command lightOnCommand = new LightOnCommand(light);
        Command lightOffCommand = new LightOffCommand(light);

        RemoteControl remoteControl = new RemoteControl();
        remoteControl.setCommand(lightOnCommand);
        remoteControl.pressButton();

        remoteControl.setCommand(lightOffCommand);
        remoteControl.pressButton();
    }
}

위 코드에서는 Light 객체를 켜는 LightOnCommand와 끄는 LightOffCommand를 객체화하여 RemoteControl 객체에 전달합니다. RemoteControl은 전달받은 명령을 실행하는 역할을 합니다. 이렇게 하면 실제로 Light 객체를 직접 컨트롤하는 코드를 작성하지 않아도 됩니다. 이는 유지보수성을 높일 뿐 아니라 코드 양을 줄여 개발속도를 높일 수 있게 합니다.

이렇게 Command Pattern을 활용하면 명령을 객체화하여 실행 취소, 재실행 등의 기능을 제공하는데 매우 효과적입니다. 이 패턴은 코드 유지보수성을 높이고 개발속도를 높이는데 큰 역할을 합니다. 이제 여러분도 Command Pattern을 활용하여 유지보수성을 높이고 개발속도를 향상시켜 보세요!

Reference : Command Pattern: 명령을 객체화하여 실행 취소, 재실행 등의 기능을 제공하는 디자인 패턴

Decorator Pattern이란?

Decorator Pattern은 객체의 기능을 동적으로 확장하기 위한 디자인 패턴입니다. 객체의 기능을 유연하게 확장하면서도 기존 코드의 수정 없이 구현할 수 있습니다. 이 패턴은 객체 지향 디자인 원칙 중 하나인 개방-폐쇄 원칙(Open-Closed Principle)을 준수합니다. 이 원칙은 기능 확장에 대해 개방되어 있으나, 수정에 대해 폐쇄되어 있어야 한다는 것입니다. Decorator Pattern은 이 원칙을 따르면서도 객체의 기능 확장을 가능하게 합니다.

객체 기능 동적 확장을 위한 디자인 패턴

Decorator Pattern은 객체의 기능을 동적으로 확장할 때 유용합니다. 이 패턴은 객체에 새로운 기능을 추가하고자 할 때, 기존 코드의 수정 없이 새로운 기능을 추가할 수 있도록 합니다. 이를 위해, Decorator 클래스를 사용합니다.

Decorator 클래스는 객체를 래핑하고, 래핑된 객체의 기능을 확장합니다. 실제로 사용되는 객체와 동일한 인터페이스를 구현합니다. Decorator 클래스는 생성자에서 래핑할 객체를 받아서, 이 객체의 기능을 확장합니다. 기존 객체의 기능을 변경하지 않고 새로운 기능을 추가할 수 있습니다.

Java 코드를 통해 Decorator Pattern을 살펴보겠습니다. 예를 들어, 커피에 물, 우유, 설탕 등을 추가하는 경우를 생각해보겠습니다. 먼저, 커피를 나타내는 인터페이스를 만듭니다.

public interface Coffee {
    public String getDescription();
    public double getCost();
}

다음으로, 커피 객체를 구현합니다.

public class SimpleCoffee implements Coffee {
    public String getDescription() {
        return "Simple coffee";
    }
    public double getCost() {
        return 1.0;
    }
}

이제 Decorator 클래스를 만들어서 커피에 물, 우유, 설탕 등을 추가할 수 있습니다.

public abstract class CoffeeDecorator implements Coffee {
    protected final Coffee decoratedCoffee;
    public CoffeeDecorator(Coffee decoratedCoffee) {
        this.decoratedCoffee = decoratedCoffee;
    }
    public String getDescription() {
        return decoratedCoffee.getDescription();
    }
    public double getCost() {
        return decoratedCoffee.getCost();
    }
}

이제 물, 우유, 설탕을 추가하는 Decorator 클래스를 만들어봅시다.

public class MilkDecorator extends CoffeeDecorator {
    public MilkDecorator(Coffee decoratedCoffee) {
        super(decoratedCoffee);
    }
    public String getDescription() {
        return super.getDescription() + ", Milk";
    }
    public double getCost() {
        return super.getCost() + 0.5;
    }
}
public class SugarDecorator extends CoffeeDecorator {
    public SugarDecorator(Coffee decoratedCoffee) {
        super(decoratedCoffee);
    }
    public String getDescription() {
        return super.getDescription() + ", Sugar";
    }
    public double getCost() {
        return super.getCost() + 0.2;
    }
}
public class WaterDecorator extends CoffeeDecorator {
    public WaterDecorator(Coffee decoratedCoffee) {
        super(decoratedCoffee);
    }
    public String getDescription() {
        return super.getDescription() + ", Water";
    }
    public double getCost() {
        return super.getCost() + 0.1;
    }
}

이제 커피 객체에 물, 우유, 설탕을 추가할 수 있습니다.

Coffee simpleCoffee = new SimpleCoffee();
System.out.println(simpleCoffee.getDescription() + " $" + simpleCoffee.getCost());

Coffee milkCoffee = new MilkDecorator(simpleCoffee);
System.out.println(milkCoffee.getDescription() + " $" + milkCoffee.getCost());

Coffee sugarMilkCoffee = new SugarDecorator(milkCoffee);
System.out.println(sugarMilkCoffee.getDescription() + " $" + sugarMilkCoffee.getCost());

Coffee waterSugarMilkCoffee = new WaterDecorator(sugarMilkCoffee);
System.out.println(waterSugarMilkCoffee.getDescription() + " $" + waterSugarMilkCoffee.getCost());

결과는 다음과 같습니다.

Simple coffee $1.0
Simple coffee, Milk $1.5
Simple coffee, Milk, Sugar $1.7
Simple coffee, Milk, Sugar, Water $1.8

이처럼 Decorator Pattern을 사용하면, 기존 코드를 수정하지 않고 객체의 기능을 동적으로 확장할 수 있습니다.

Decorator Pattern은 객체의 기능을 확장할 때 유용한 디자인 패턴입니다. 이 패턴은 기존 코드를 수정하지 않고, 객체의 기능을 동적으로 확장할 수 있는 장점이 있습니다. 이를 위해 Decorator 클래스를 사용하며, 래핑된 객체의 기능을 확장합니다. Decorator Pattern은 개방-폐쇄 원칙을 준수하면서도, 유연한 기능 확장을 가능하게 합니다.

Reference : Decorator Pattern: 객체의 기능을 동적으로 확장하기 위한 디자인 패턴

+ Recent posts