Command Pattern (커맨드 패턴)

Command Pattern

 

정의

command pattern을 이용하면 요구사항을 객체로 캡슐화 하여, 요구사항을 나중에 이용할 수 있도록 메소드 이름과 매개변수 등 요구사항에 필요한 정보를 집어넣을 수 있다. 요청내역을 큐에 저장하거나 로그를 기록할 수 있으며, 작업취소 기능도 있다.

 

구성

1.    Client : Client ConcreteCommand를 생성하고 Receiver를 설정한다.

2.    Receiver : 요구사항을 수행하기 위해 어떤 일을 처리하는 객체

3.    Invoker : 명령이 있으며 execute() 메소드를 호출하여 커맨드 객체에게 특정 작업을 수행하도록 요청

4.    Command : 모든 커맨드 객체가 구현할 Interface. Receiver에게 시킬 모든 명령은 execute()메소드를 호출함으로써 수행되며, Receiver에게 특정 작업을 처리하라는 지시를 내린다.

5.    ConcreteCommand : 특정 행동과 Receiverbind한다. Invoker에서 execute()메소드 호출을 통해 요청하고 ConcreteCommand 객체에서는 Receiver에 있는 메소드를 호출함으로써 작업을 처리한다.


 

구현방법

1.    기능Class(Receiver)들을 캡슐화 한다.

2.    기능Class를 외부에 작동할 수 있는 Command (interface or class)를 추상화 및 구현한다.

3.    기능실행class(Invoker) command 타입 객체로 구현한다.

4.    기능실행class(Invoker) setter method를 구현하여 Command 타입 object를 가져오도록 한다.

5.    Invoker Object, Receiver Object, Command 타입의 Receiver Objectparameter로 하는 Object들을 생성한다.

6.    Invoker Object에서 Setter method를 호출하여 해당 commandAction Object를 등록하고, invoker에서 Command execute할 수 있는 method를 호출한다.

 

특징

request부와 execute부를 분리하고, undo, 보관, log생성이 가능하다.

장점

Receiver Command만 추가하면 dynamic하게 object 호출이 가능하다.

단점

Object 구성부가 추가되면 abstract부분부터 수정해야 한다.


 

Client 소스

public class RemoteLoader {

         public static void main(String[] args) {

                 RemoteControl remoteControl = new RemoteControl();

                 CeilingFan ceilingFan = new CeilingFan("Living Room");

                 CeilingFanHighCommand ceilingFanHigh = new CeilingFanHighCommand(ceilingFan);

                 CeilingFanOffCommand ceilingFanOff = new CeilingFanOffCommand(ceilingFan);

                 remoteControl.setCommand(2, ceilingFanHigh, ceilingFanOff);

                 System.out.println(remoteControl);

                 remoteControl.onButtonWasPushed(0);

                 remoteControl.offButtonWasPushed(0);

                 remoteControl.undoButtonWasPushed();

                 remoteControl.onButtonWasPushed(2);

                 remoteControl.offButtonWasPushed(2);

                 remoteControl.undoButtonWasPushed();

         }

}


Receiver 소스

/**
 * Receiver (천장의 FAN 작동시킨다)
 */
public class CeilingFan {
         public static final int HIGH=3;
         public static final int MEDIUM=2;
         public static final int LOW=1;
         public static final int OFF=0;
         String location;
         int speed;
         public CeilingFan(String location) {
                 // TODO Auto-generated constructor stub
                 this.location=location;
                 speed=OFF;
         }
         public void high(){
                 speed = HIGH;
         }
         public void medium(){
                 speed = MEDIUM;
         }
         public void low(){
                 speed = LOW;
         }
         public void off(){
                 speed = OFF;
         }
         public int getSpeed(){
                 return speed;
         }
}


 

Invoker

/**
 * Invoker
 */
public class RemoteControl {
         Command[] onCommands;
         Command[] offCommands;
         Command undoCommand;
         public RemoteControl() {
                 // TODO Auto-generated constructor stub
                 onCommands = new Command[7];
                 offCommands = new Command[7];
 
                 Command noCommand = new NoCommand();
                 for(int i=0; i<7; i++){
                          onCommands[i] = noCommand;
                          offCommands[i] = noCommand;
                 }
                 undoCommand = noCommand;
         }
         /**
          * @param slot
          * @param onCommand
          * @param offCommand
          * 리모컨의  slot command 넣는다.
          */
         public void setCommand(int slot, Command onCommand, Command offCommand) {
                 onCommands[slot] = onCommand;
                 offCommands[slot] = offCommand;
         }
         /**
          * @param slot
          * slot ON button 눌리면  slot OnCommand execute()메소드가 호출된다.
          */
         public void onButtonWasPushed(int slot) {
                 onCommands[slot].execute();
                 undoCommand = onCommands[slot];
         }
         public void offButtonWasPushed(int slot) {
                 offCommands[slot].execute();
                 undoCommand = offCommands[slot];
         }
         @Override
         public String toString() {
                 StringBuffer stringBuffer = new StringBuffer();
                 stringBuffer.append("\n-----Remote Control-----\n");
                 for(int i=0; i<onCommands.length; i++){
                          stringBuffer.append("[slot " + i + "] " + onCommands[i].getClass().getName()+"\n");
                 }
                 return stringBuffer.toString();
         }
         public void undoButtonWasPushed() {
                 // TODO Auto-generated method stub
                 undoCommand.undo();
         }
}


Command 소스 (fan의 속도를 높임)

/**
 *  class fan 속도를 높이고, Receiver CeilingFan 사이를 bind한다.
 */
public class CeilingFanHighCommand implements Command{
         CeilingFan ceilingFan;
         int prevSpeed;
 
         public CeilingFanHighCommand(CeilingFan ceilingFan) {
                 // TODO Auto-generated constructor stub
                 this.ceilingFan=ceilingFan;
         }
         
         /* 
          * Invoker에서 execute 호출하면 fan 속도를 높인다.
          * unDo 구현하기 위해 prevSpeed 속도 값을 저장해 둔다.
          */
         @Override
         public void execute() {
                 // TODO Auto-generated method stub
                 prevSpeed = ceilingFan.getSpeed();
                 ceilingFan.high();
         }
         
         /* 
          * prevSpeed 기준으로 speed 설정한다.
          */
         @Override
         public void undo() {
                 // TODO Auto-generated method stub
                 if(prevSpeed == CeilingFan.HIGH){
                          ceilingFan.high();
                 }else if (prevSpeed == CeilingFan.MEDIUM){
                          ceilingFan.medium();
                 }else if (prevSpeed == CeilingFan.LOW){
                          ceilingFan.low();
                 }else if (prevSpeed == CeilingFan.OFF){
                          ceilingFan.off();
                 }
         }
}


 

Command소스 (Fan의 속도를 설정)

public class CeilingFanOffCommand implements Command{
         CeilingFan ceilingFan;
         int prevSpeed;
 
         public CeilingFanOffCommand(CeilingFan ceilingFan) {
                 // TODO Auto-generated constructor stub
                 this.ceilingFan = ceilingFan;
         }
 
         @Override
         public void execute() {
                 // TODO Auto-generated method stub
                 prevSpeed = ceilingFan.getSpeed();
                 ceilingFan.off();
         }
 
         @Override
         public void undo() {
                 // TODO Auto-generated method stub
                 if(prevSpeed == CeilingFan.HIGH){
                          ceilingFan.high();
                 }else if(prevSpeed==CeilingFan.MEDIUM){
                          ceilingFan.medium();
                 }else if(prevSpeed==CeilingFan.LOW){
                          ceilingFan.low();
                 }else if(prevSpeed==CeilingFan.OFF){
                          ceilingFan.off();
                 }
         }
}

 

Command

/**
 *  class null object이다.
 * return object 없어도 client에서 null 처리하지 않아도
 * 되게   사용한다.
 */
public class NoCommand implements Command{
         @Override
         public void execute() {
                 // TODO Auto-generated method stub
 
         }
         @Override
         public void undo() {
                 // TODO Auto-generated method stub
 
         }
 
}


Interface

/**
 * 모든 command에서 구현해야 하는 interface이다.
 * 모든 command execute method 통해서 호출되며,
 *  method에서는 receiver 특정 작업을 처리하게 한다.
 */
public interface Command {
         public void execute();
         public void undo();
}

 


구현


Factory Pattern (팩토리 패턴)

Factory Pattern



모든 factory pattern에서는 app의 구상 클래스에 대한 dependency를 줄여줘서 loose-coupling을 도와준다. 또한 Object 생성을 encapsulation 한다. 주로, Super-class와 다수의 sub-class가 있을 때 input을 기준으로 하나의 sub-class를 반환할 경우 사용한다. 구상 class가 아닌 추상 class/interface에 맞춰서 코딩할 수 있게 해주는 강력한 기법이다.

 


  Simple Factory

    디자인 패턴이라 할 수 없고, 자주 쓰이는 관용구라 할 수 있다. Client와 구상 class를 분리시키기 위한 간단한 기법으로 활용한다.

 


  Factory Method Pattern

    Object를 생성하기 위한 Interface를 정의하는데, Object를 생성하는 부분을 Sub-Class에 위임하는 pattern이다. ‘new’키워드를 호출하는 부분을 Sub-Class에 위임하는 것이다. 그 결과, class간의 결합도(class의 변경이 있을 경우, 다른 class에 영향을 주는 정도)가 떨어진다. SimpleFactory와의 차이점은 Factory Method Pattern은 어떤 구현을 사용할지를 sub-class에서 결정하는 framework를 만들 수 있다는 것이다. SimpleFactory에서도 Object생성을 Encapsulation하는 방법을 사용하긴 하지만 생성하는 제품을 마음대로 변경할 수 없기 때문에 Factory Method Pattern처럼 강력한 flexibility를 제공하지는 못한다.

 


  Abstract Factory Pattern

    Interface를 이용하여, 연관성이 있는 많은 sub-class를 특정 그룹으로 묶어 일괄적으로 수정할 수 있도록 하는 pattern이며, 제품을 추가하려면 Interface를 수정하면 된다. 예를 들어 특정 library를 배포하는데 국가마다 기능이 상이하다면 abstract factory pattern을 이용해서 일괄적으로 기능을 변경하여 대처할 수 있다.

 


●  Dependency Inversion Principle

   추상화된 것에 의존하도록 하고, 구상 클래스에 의존하지 않도록 해야 한다.


1.    어떤 변수에도 구상 클래스에 대한 reference를 지정하지 않는다(new 연산자를 사용하는 것이 reference를 사용하게 되는 것)

2.    구상 클래스에서 유도된 클래스를 만들지 않는다. (구상클래스에서 유도된 클래스를 만들면 특정 구상 클래스에 의존하게 된다. 추상화된 것을 사용해야 한다.)

3.    클래스에 이미 구현된 메소드를 override 하지 않는다. (이미 구현된 메소드를 override 한다는 것은 클래스가 제대로 abstract 되지 않았다고 할 수 있다. 클래스에 method를 정의할 때에는 모든 sub-class에서 공유할 수 있는 것으로 정의해야 한다.



 

구현


Decorator Pattern (데코레이터 패턴)

Decorator Pattern

 

정의

상속 또는 interface 이용하여 Type 맞춰 객체의 추가적인 요건을 동적으로 추가한다. 서브클래스(decorator class) 만드는 것을 통해서 기능을 유연하게 확장할 있는 방법을 제시한다. 중요한점은 Decorator 상속을 통해서 행동을 물려받는 것이 목적이 아니라는 것이다.

 


구성

1.    구성요소는 직접 쓰일 수도 있고 decorator 감싸져서 쓰일 있다.

2.    ConcreteComponent 새로운 행동을 동적으로 추가하게 된다.

3.    decorator 안에는 Component 객체가 들어있다.

4.    Decorator 자신이 decorate 구성요소와 같은 interface abstract class implement 한다.

5.    Decorator component 상태를 확장할 있다.

6.    ConcreteDecorator에는 Object decorate하고 있는 것을 위한 interface 변수가 있다.

7.    decorator에서 새로운 method 추가할 있다.

 

l  OCP (Open-Closed Principle) : class 확장에 대해서는 open 해야 하지만 코드 수정에 대해서는 close 해야 한다. 기존 코드는 건드리지 않은 채로 확장을 통해서 새로운 행동을 추가할 있도록 코드의 수정을 허용한다는 것으로 기능 추가에 유연하기에 튼튼한 디자인을 있다.


 

장점

1.    기존 코드를 수정하지 않고도 행동을 확장하는 방법이 된다.

2.    Composition delegate 통해서 실행 중에 새로운 행동을 추가할 있다.

3.    상속대신 decorator pattern 통해서 행동을 확장할 있다.

4.    OCP 충실하면서 유연한 디자인을 만들어 있다.

 


단점

1.    잡다한 클래스들이 많아 있다.

2.    객체가 다른 객체들로 쌓여 있을 있기 때문에 파악하기 힘들 있다.

3.    디자인 유연성 면에서는 좋지 않다.

 


구현 (Coffee 제조)


'SW > DesignPattern' 카테고리의 다른 글

Singleton Pattern (싱글턴 패턴)  (0) 2017.09.05
Factory Pattern (팩토리 패턴)  (0) 2017.09.05
Observer Pattern (옵저버 패턴)  (0) 2017.09.05
Strategy Pattern (스트레테지 패턴)  (0) 2017.09.05
DesignPattern이란? 왜쓰지?  (0) 2017.09.05

Observer Pattern (옵저버 패턴)

Observer pattern

 

정의

객체의 상태가 바뀌면 객체에 의존하는 다른 객체들이 자동으로 갱신되는 방식으로 객체들 간에 one-to-many 의존성을 정의한다. 객체의 상태 변화를 관찰하는 Observer들을 객체에 등록하여 상태 변화가 있을 경우 객체가 메소드를 통해 Observer들에게 알리는 Design pattern이다. 주로 분산 이벤트 핸들링을 구현하는데 사용하거나, 하나의 객체에 여러 개가 의존할 경우 사용하는 것이 대부분이다.

 

l  자바에는 java.util.Observable이라는 API 있다. 하지만 interface 아니라 class이기에 이미 다른 super class extends하고 있는 class에서는 사용할 없다는 점과, 직접 구현이 불가능하다는 단점이 존재한다. 그리고, 핵심 method(‘setChange()’) protected 선언이 되어있기때문에 해당 method 외부에서 사용하는 것이 불가능하다 라는 단점이 있다.

 


조건

Loose-Coupling : 필요한 이유는 객체 간의 결합도가 높아질수록 유지보수는 힘들기 때문이다.  Loose-Coupling 특징으로는 주체가 observer 대해서 observer interface implement하고 있다는 점을 제외하고는 있는 정보가 없다. Loose-Coupling 장점은 Observer 언제든지 추가할 있고, 새로운 Observer 해도 주체를 변경할 필요가 없으며 주체와 observer 독립적으로 사용할 있다. 또한 Observer 바뀌어도 서로 영향을 미치지 않는다는 것이다.


 

구성

 2개의 역할을 하는 interface(subject, observer) 생성한다. subject라는 interface observer들을 관리하는 method들을 가진다. method들은 observer add, delete, notifyObserver 이렇게 3가지 역할을 한다. Observer interface 정보를 업데이트 해주는 update method 가진다. Subject implment class 정보를 제공하는 subject 되며 observer 객체들을 가진다. 그리고 observer interface implement class notifyObserver method 호출하면서 알려줄 때마다 update method 호출된다.

 


정리

1.    Observer pattern object state 바뀌면 해당 object 의존하는 다른 object들에게 신호를 보내고 자동으로 정보가 갱신되는 1:N 관계를 가진다.

2.    연결은 interface 이용하여 loose-coupling 유지한다.

3.    Observer pattern push 방식(주체 object에서 observer 데이터를 보내는 방식) pull 방식(observer에서 주체 object 데이터를 가져가는 방식)으로 언제든지 구현할 있다.

4.    JAVA에서는 Observable class Observer interface 제공한다.


 

구현 (팬관리)


Strategy Pattern (스트레테지 패턴)

Strategy Pattern

 

정의

어떤 동작을 하는 알고리즘을 정의하고 각각을 Encapsulation하고 Delegate를 통해서 어떤 행동을 할지 결정하는 패턴이다. Strategy pattern을 이용하면 알고리즘을 사용하는 client는 독립적으로 알고리즘을 변경할 수 있다. 상속보다는 구성을 이용한다. ‘AB보다는 ‘A B가 있다라는 패턴이다. 정리하자면, 하나의 결과를 만드는 목적은 동일하나, 그 목적을 달성할 수 있는 방법이 여러가지 존재할 경우 기본이 되는 template method와 함께 많이 사용되는 패턴이다.

 


사용하기 좋은 경우

1.    행동만 조금씩 다를 뿐 관련된 class가 많을 때

2.    알고리즘의 변형이 필요할 때

3.    User가 몰라야 하는 data를 사용하는 알고리즘이 있을 때

4.    하나의 class가 많은 행동을 정의하고, 이런 행동들이 그 class의 연산 안에서 복잡한 조건문의 형태일 때

 

 

구성

1.    여러 개의 sort algorithm을 정의하고 필요에 따라 선택적으로 적용한다.

2.    App에서 달라지는 부분을 찾아내어, 그렇지 않은 부분으로부터 분리한다.

3.    구현이 아닌 interface에 맞춘다.

4.    inheritance보단 composition을 활용한다.

 


장점

1.    알고리즘을 Encapsulation 시켰기 때문에 확장성이 좋다.

2.    프로그램이 실행 중에 알고리즘을 setting할 수 있다.

3.    로직을 독립적으로 관리하기 쉽다는 장점이 있다.

4.    코드의 중복을 줄일 수 있다.

 


단점

Strategy Object Context Object 사이 의사소통에 overhead가 있다.


    UML

   


'SW > DesignPattern' 카테고리의 다른 글

Singleton Pattern (싱글턴 패턴)  (0) 2017.09.05
Factory Pattern (팩토리 패턴)  (0) 2017.09.05
Decorator Pattern (데코레이터 패턴)  (0) 2017.09.05
Observer Pattern (옵저버 패턴)  (0) 2017.09.05
DesignPattern이란? 왜쓰지?  (0) 2017.09.05

DesignPattern이란? 왜쓰지?

Design Pattern

 

정의 

방식을 통해 SW 설계에서 얻은 세세한 경험들을 기록해 놓도록 하는 것으로 특정한 상황에서 구조적인 문제에 대한 해법이라 할 수 있다. 그 중에서도 anti-pattern이라는 것이 있는데, 이는 실제로 많이 쓰는 pattern이지만, 비효율적이고, 비생산적인 pattern을 뜻한다. 일반적으로 하나의 패턴에는 다음 4가지 요소가 들어가 있다.


1.    Pattern name은 한두 단어로 설계 문제와 해법을 서술한다.

A.     패턴의 이름을 정의해 두면 문서에서 이 이름을 사용하여 설계의 의도를 표현하기가 편리하다. 또한, 설계에 대한 생각이 쉽고, 개발자들 간의 communication이 원활해 진다.

2.    문제는 언제 패턴을 사용하는가를 서술하며 해결할 문제와 그 background를 설명한다

A.     어떤 알고리즘을 이용하여 객체를 생성할까와 같은 설계의 세세한 문제를 설명할 수 있다.

3.    Solution은 설계를 구성하는 요소와 그 요소들 사이의 관계들의 책임, 협력 관계를 서술한다.

A.     어떤 구체적인 설계와 구현을 설명하는 것은 아니다. 그 이유는 pattern은 다양한 경우에 적용할 수 있는 template이기 때문이다. Design pattern은 구체적인 부분이 아닌 추상적인 설명을 주고 해결하기 위한 클래스와 객체들의 열거 방법을 제시한다.

4.    결과는 design pattern을 통해 얻을 수 있는 결과와 장점, 그리고 단점을 서술한다.

A.     설계를 결정할 때에는 설계의 결과를 고려하여야 한다. 여기서 결과는 시공간의 효율을 중요한 요소로 볼 것인지에 따라서 다른 설계 방법을 택해야 한다. ReuseOOP설계의 주요소이기 때문에 pattern의 결과는 system의 유연성, 이식성, 확장성 등에 큰 영향을 끼친다.

 


디자인 패턴이 필요한 이유

1.    코드가 명확하고 가독성이 좋아진다.

2.    모듈(class, function, etc.)은 한가지 기능만 하도록 세분화 된다.

3.    재사용성이 높아진다.

4.    유지보수가 쉬워진다.

5.    리소스의 낭비가 적어진다.

'designpattern'에 해당되는 글 6건

1 →