객체의 상태를 캡슐화하고 상태 전환을 관리하기 위한 디자인 패턴인 State Pattern에 대해 알아보겠다.

State Pattern란?

State Pattern은 객체의 상태를 캡슐화하고 이를 통해 상태 전환을 관리하는 디자인 패턴이다. 객체는 다양한 상태를 가질 수 있으며, 이러한 상태들은 객체의 행동을 결정하게 된다. State Pattern은 이러한 상태들을 독립적인 클래스로 구현하고, 이를 객체의 상태에 따라서 교체할 수 있도록 한다.

State Pattern은 객체의 상태 전환 로직을 캡슐화함으로써 코드의 유연성과 확장성을 높일 수 있다. 예를 들어, 상태가 추가되거나 변경되더라도 해당 상태 클래스만 수정하면 되기 때문에 다른 코드에 영향을 미치지 않는다. 또한, 객체의 특정 상태에서만 가능한 행동을 구현할 수 있기 때문에 코드의 안정성도 높아지게 된다.

State Pattern의 장점과 활용 방법

State Pattern의 가장 큰 장점은 객체의 상태 전환을 효율적으로 관리할 수 있다는 점이다. 객체가 여러 상태를 가질 수 있고, 이 상태들이 객체의 행동을 결정하기 때문에 이를 효율적으로 관리할 수 있는 방법이 필요하다. State Pattern은 이를 해결하기 위한 방법 중 하나이다.

State Pattern의 활용 방법은 다양하다. 예를 들어, 자판기 기능을 구현할 때 State Pattern을 사용할 수 있다. 자판기는 여러 상태를 가지고 있으며, 사용자의 동작에 따라 상태를 전환해야 한다. 이러한 상황에서 State Pattern을 사용하면 자판기의 코드를 간결하고 유지보수하기 쉽게 구현할 수 있다.

Java 코드로 보면 다음과 같다.

public interface State {
  void doAction(Context context);
}

public class StartState implements State {

  public void doAction(Context context) {
    System.out.println("Player is in start state");
    context.setState(this);
  }

  public String toString(){
    return "Start State";
  }
}

public class StopState implements State {

  public void doAction(Context context) {
    System.out.println("Player is in stop state");
    context.setState(this);
  }

  public String toString(){
    return "Stop State";
  }
}

public class Context {
  private State state;

  public Context(){
    state = null;
  }

  public void setState(State state){
    this.state = state;     
  }

  public State getState(){
    return state;
  }
}

위의 코드에서 State는 상태를 나타내는 인터페이스이며, StartState와 StopState는 상태를 구현한 클래스이다. Context는 객체의 상태를 관리하는 클래스로, 상태를 변경할 때마다 상태를 갱신하게 된다.

State Pattern은 객체의 상태를 효율적으로 관리하기 위한 디자인 패턴으로, 객체가 가지는 여러 상태를 독립적인 클래스로 구현하고, 이를 통해 객체의 상태 전환을 관리한다. 이를 통해 코드의 유연성과 확장성을 높일 수 있으며, 객체의 안정성을 높일 수 있다. State Pattern은 다양한 분야에서 활용될 수 있으며, 예제 코드를 통해 쉽게 이해할 수 있다.

Reference : State 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