[DesignPattern] Decorator Pattern

2014. 1. 27. 09:28Architecture/DesignPattern

반응형

Decorator Pattern


 개요

 클래스 다이어그램

 예제(Java)

 같이보기

 참고 사항


<< 개요 >>

Decorator Pattern 이란?

 

데코레이터 패턴(Decorator pattern)이란 주어진 상황 및 용도에 따라 어떤 객체에 책임을 덧붙이는 패턴으로, 기능 확장이 필요할 때 서브클래싱 대신 쓸 수 있는 유연한 대안이 될 수 있다.

(출처 : 위키피디아 - http://ko.wikipedia.org/wiki/%EB%8D%B0%EC%BD%94%EB%A0%88%EC%9D%B4%ED%84%B0_%ED%8C%A8%ED%84%B4)

 

의도

객체에 동적으로 새로운 서비스를 추가

기능 추가를 위해 서브클래스를 생성 하는 것 보다 융통성이 있음.

 

 

아래의 로봇 사진 출처 : http://blog.naver.com/PostView.nhn?blogId=romantico_q&logNo=50185115988

 

변신 합체 로봇!! 페가서스 라고 하네요^^;;

데코레이터 패턴을 학습 하면서 기억에 많이 남을만한 예제가 없을까? 라고 생각하던 차에..변신합체 로봇을 통해 학습하면 좋겠다고 생각하게 되었습니다..ㅋㅋㅋㅋ;;

 

우리의 변신합체 로봇들을 소개 합니다.

우리의 메인 로봇인 왼쪽 - 파랭이 로봇!!

그 외 몸통이 될 가운데 로봇, 다리가 되어줄 빨갱이 로봇ㅋㅋ

 

하일라이트로 다시 한번 변신을 시켜줄 우리의 독수리 로봇이 되겠습니다.

 

 

 

1) 머리(우리의 메인)

 

2) 몸통(합체 되어질)

 

3) 다리(합체 되어질)

 

 

쫘잔~~~+ㅁ+/

 

 

 

아래처럼 합체로봇으로 변신하게 됩니다.

 

 

여기서 다가 아닙니다!! 변신합체 로봇에서 다시 한번 독수리가 합체가 되어서

그 유명한!! 페가서스가 되어집니다!!!! 쫘잔~~~~~~+ㅁ+/

 

변신합체 로봇! 페가서스!!!! 두둥~

자! 데코레이터 패른!!! 시작 해볼까용?~~

개요는 마무리 하고, 먼저 패턴의 클래스 다이어그램을 먼저 살펴 보겠습니다.

 

<< 클래스 다이어그램 >> 

그냥 한번 그려보았다..;;

 

아래와 비교해보면 인터페이스와 추상클래스간의 관계를 그리지 않은 것 같다. 참고하자!

 

<< 예제(Java) >>

1) 결과

   아래의 결과와 같이 변신은 메인 로봇이 머리로! 그 다음엔 바디, 그 다음 다리, 그 다음 뒷다리로 변신이

   되어집니다. ㅋㅋㅋ 전투력은 무려 10만이 넘어가네요+ㅁ+/

Change Center Robot -> Body Combine!!
Change Red Robot -> Combine Leg!!!
Change egle Robot -> Back Leg Combine!!
Main Robot Combine!! to Head, Combine Body!!, Combine Leg!!, Combine Back Leg!!
total power is..103100

 

 

    2) 테스트 코드   

package kr.pe.acet.decorator;

import org.junit.Assert;
import org.junit.Test;

public class DecoratorPatternTest {

 @Test
 public void test() {
  
  Robot mRobot = new BacklegCombine(new LegCombine(new BodyCombine(new  MainRobot())));
  
  Assert.assertNotNull(mRobot);
  
  System.out.println(mRobot.getCombineAction());
  System.out.println("total power is.."+mRobot.getPower());
  
 }

}

 

 

    3) Robot Interface(Decorator pattern에서 중요하게 봐야 할 부분 입니다.)

package kr.pe.acet.decorator;

public interface Robot {
 public String getCombineAction();
 public int getPower();
}
 

 

 

 

    4) MainRobot class

package kr.pe.acet.decorator;

public class MainRobot implements Robot{

 @Override
 public String getCombineAction() {
  // TODO Auto-generated method stub
  return "Main Robot Combine!! to Head";
 }

 @Override
 public int getPower() {
  // TODO Auto-generated method stub
  return 100;
 }
}
 

 

 

    5) CombineDecorator class (Decorator pattern에서 중요하게 봐야 할 부분 입니다.)

package kr.pe.acet.decorator;

public abstract class CombineDecorator implements Robot{
 protected Robot tempRobot;
 
 public CombineDecorator(Robot newRobot){
  tempRobot = newRobot;
 }
 
 public String getCombineAction() {
  // TODO Auto-generated method stub
  return tempRobot.getCombineAction();
 }

 public int getPower() {
  // TODO Auto-generated method stub
  return tempRobot.getPower();
 }
  
}
 

 

 

    6) BodyCombine class

package kr.pe.acet.decorator;

public class BodyCombine extends CombineDecorator{

 public BodyCombine(Robot newRobot) {
  super(newRobot);
  System.out.println("Change Center Robot -> Body Combine!!");
 }

 public String getCombineAction() {
  // TODO Auto-generated method stub
  return tempRobot.getCombineAction()+", Combine Body!!";
 }

 public int getPower() {
  // TODO Auto-generated method stub
  return tempRobot.getPower()+2000;
 }

}
 

 

 

    7) LegCombine class

package kr.pe.acet.decorator;

public class LegCombine extends CombineDecorator{

 public LegCombine(Robot newRobot) {
  super(newRobot);
  System.out.println("Change Red Robot -> Combine Leg!!!");
 }
 
 public String getCombineAction() {
  // TODO Auto-generated method stub
  return tempRobot.getCombineAction()+", Combine Leg!!";
 }

 public int getPower() {
  // TODO Auto-generated method stub
  return tempRobot.getPower()+1000;
 }

}
 

 

 

 8) BacklegCombine class

package kr.pe.acet.decorator;

public class BacklegCombine extends CombineDecorator{

 public BacklegCombine(Robot newRobot) {
  super(newRobot);
  System.out.println("Change egle Robot -> Back Leg Combine!!");
 }

 public String getCombineAction() {
  // TODO Auto-generated method stub
  return tempRobot.getCombineAction()+", Combine Back Leg!!";
 }

 public int getPower() {
  // TODO Auto-generated method stub
  return tempRobot.getPower()+100000;
 }

}
 

 

 

 

<< 같이 보기 >>

http://www.youtube.com/watch?v=j40kRwSm4VE

정말 도움이 많이 된 동영상 입니다. 참고하세요~꼭 보세요~!!

내 책에 있던 소스 코드

 

또 다른 소스 참고! : https://github.com/colorbox/Gof/tree/master/java/Decorator

 

<< 참고 사항 >>

데코레이터 패턴은 객체에 동적으로 새로운 무엇인가를 하고자 할 때 사용 된다. 특히 상속으로 sub Class를 이용하는 것 보다 더 유연성 있게 추가 할 수 있다.

 

 

 

반응형