Compound Pattern (컴파운드 패턴)

Compound Pattern

 

정의


반복적으로 생길 수 있는 일반적인 문제를 해결하기 위한 용도로 두 개 이상의 디자인패턴을 결합하여 사용하는 것이다.


또한, 여러 패턴을 같이 사용한다고 해서 compound pattern이 되는 것이 아닌, 문제를 해결하기 위한 용도로 사용하여야 한다.

 


시나리오


1.    Duck들이 있었는데, Goose가 등장하여 자신도 Quackable이 되고 싶다고 요청


A.     Adapter Pattern을 이용하여 goosequackable에 맞게 구현하여 goose객체의 quack()를 호출하면 자동으로 honk()가 호출된다.


2.    학자들이 quack소리의 횟수를 세고 싶다고 함


A.     Decorator Pattern을 이용하여 QuackCounter decorator를 추가하였다


Quack() 메소드 호출 자체는 그 decorator로 쌓여 있는 Quackable에 의해 처리되고 quack()의 호출된 횟수를 셀 수 있게 되었다.


3.    QuackCounterdecorator 되지 않은 Quackable Object 문제


A.     Abstract factory pattern을 적용하여 object를 만들도록 구성한다.


4.    모든 duck goose, Quackable Object들을 관리하는데 무리가 생김


A.     Composite Pattern을 이용하여 duck을 모아서 ducks로 관리


B.     Iterator를 통하여 반복작업까지 처리할 수 있게 됨


5.    Quackable에서 quack를 호출하였다는 signal을 받고 싶어함


A.     Observer Pattern을 이용하여 QuackologistQuackable observer로 등록하여 signal을 받게 되었으며, signal을 돌릴 때 iterator pattern을 적용하였다.

 


소스코드


interface


//Quckable interface
public interface Quackable {
   
public void quack();
}

 

Duck object


//implement Quackable interface
public class MallardDuck implements Quackable {
   
@Override
    public void
quack() {
       
System.out.println("Quack");
    }
}
public class RedheadDuck implements Quackable {
   
@Override
    public void
quack() {
       
System.out.println("quack");
    }
}
public class RubberDuck implements Quackable{
   
@Override
    public void
quack() {
       
System.out.println("Squeak");
    }
}
public class DuckCall implements Quackable{
   
@Override
    public void
quack() {
       
System.out.println("Kwak");
    }
}

 

GooseAdapter

//goose adapter to bind Duck class
/*
class interface client에서 사용하고 하는 다른 interface로 변환한다.
adapter
를 이용하면 interface의 호환성 문제 때문에 같이 사용할 수 없는 class를 쓸 수 있다.
 */
public class GooseAdapter implements Quackable {

   
Goose goose;

   
public GooseAdapter(Goose goose) {
       
this.goose = goose;
    }

   
@Override
    public void
quack() {
       
goose.honk();
    }
}

 

Goose

//add goose
public class Goose {
   
public void honk() {
       
System.out.println("Honk");
    }
}

 

Abstract factory pattern

//abstract factory pattern
//
구체적인 클래스를 지정하지 않고 관련성을 갖는 객체들의 집합을 생성하거나
//서로 독립적인 객체들의 집합을 생성할 수 있는 인터페이스를 제공한다.
public abstract class AbstractDuckFactory {

   
public abstract Quackable createMallardDuck();
   
public abstract Quackable createRedheadDuck();
   
public abstract Quackable createDuckCall();
   
public abstract Quackable createRubberDuck();
}

 

Counting duck factory

public class CountingDuckFactory extends AbstractDuckFactory{

   
@Override
    public
Quackable createMallardDuck() {
       
return new QuackCounter(new MallardDuck());
    }

   
@Override
    public
Quackable createRedheadDuck() {
       
return new QuackCounter(new RedheadDuck());
    }

   
@Override
    public
Quackable createDuckCall() {
        
return new QuackCounter(new DuckCall());
    }

   
@Override
    public
Quackable createRubberDuck() {
       
return new QuackCounter(new RubberDuck());
    }
}

 


main

//run
public class DuckSimulator {

   
public static void main(String [] args) {
        
DuckSimulator simulator = new DuckSimulator();
       
AbstractDuckFactory duckFactory = new CountingDuckFactory();
       
simulator.simulator(duckFactory);
    }


   
void simulator(AbstractDuckFactory duckFactory) {
       
Quackable mallardDuck = duckFactory.createMallardDuck();
       
Quackable redheadDuck = duckFactory.createRedheadDuck();
       
Quackable duckCall = duckFactory.createDuckCall();
       
Quackable rubberDuck = duckFactory.createRubberDuck();
       
Quackable gooseDuck = new GooseAdapter(new Goose());

       
System.out.println("\nDuck Simulator");

       
simulator(mallardDuck);
       
simulator(redheadDuck);
       
simulator(duckCall);
       
simulator(rubberDuck);
       
simulator(gooseDuck);

       
System.out.println("The Ducks quacked " + QuackCounter.getQuacks() + " times");
    }

   
void simulator(Quackable duck) {
       
duck.quack();
    }
}

 


 결과화면



UML


State Pattern (스테이트 패턴)

State Pattern

 


정의


Object의 내부 상태가 바뀜에 따라서 object의 행동을 바꿀 수 있다.


마치 object class가 바뀌는 것과 같은 결과를 얻을 수 있다.


State patternstateclass로 표현한다


그 이유는, class의 교체를 통해서 state의 변화를 나타낼 수 있고, 새로운 state를 추가해야 할 때, 편리하기 때문이다.

 


적용 영역


1.    Object의 행위가 object state에 의존하고 그 object의 행위가 실행 시점에서 object state에 따라 변화해야 할 경우


2.    Operation이 크고, objectstate에 따라 다수의 조건문을 포함하는 경우


 

State vs Strategy (pattern)


State pattern을 사용할 때는 state object의 행동이 캡슐화 된다


State에 따라 context object에서 여러 state object 중 한 object에게 모든 행동을 위임한다.


해당 object의 내부 state에 따라 현재 state를 나타내는 object가 바뀌고


그 결과 context object의 행동도 바뀐다. Clientstate object에 대해서 몰라도 된다.


하지만, strategy patternclient에서 context object한테 어떤 object를 사용할지 정한다


Strategy pattern은 주로 실행시에 전략 object를 변경할 수 있는 유연성을 제공하기 위한 용도로 쓰이며, 가장 적합한 전략 object를 선택해서 사용한다.


, strategy pattern은 외부에서 상황에 맞게 변화를 줄 수 있고, state pattern은 자신이 직접 상태변화에 관여한다는 것이다



구성요소


1.    State를 나타내는 state


2.    state간의 전의를 표현하는 action


3.    state 전이에 나타나는 onEntry, onExit 함수


 

소스코드


Action(enum)

public enum Action {
   
EAT, DIGEST, GOTOBED;
}

 

State(enum)

public enum State {
   
HUNGRY{
       
public State act(Action action){
           
switch (action){
                
case EAT: return FULL;
               
default: return null;
            }
        }
    },
   
FULL{
       
public State act(Action action){
           
switch (action){
               
case EAT: return ANGRY;
               
case DIGEST: return HUNGRY;
               
case GOTOBED: return SLEEPING;
               
default: return null;
            }
        }
    },
   
ANGRY{
       
public State act(Action action){
           
switch (action){
               
case DIGEST: return FULL;
                
default: return null;
            }
        }
    },
   
SLEEPING{
       
public void onEntry(){
           
System.out.println("go bed");
        }
       
public State act(Action action){
           
return null;
        }
    };
   
abstract State act(Action action);
   
public static State getInitState(){
       
return HUNGRY;
    }
   
public static boolean isFinalState(State state){
       
return state==SLEEPING;
    }
   
public void onEntry(){}
   
public void onExit(){}
}

 

StateContext(class)

public class StateContext {
   
private State currentState;
   
public StateContext(){
       
currentState = State.getInitState();
    }
   
public void processEvent(Action action){
       
State next= currentState.act(action);
       
if(next != null){
            
currentState.onExit();
           
System.out.println(action +"에 의해 State " +
                   
currentState+"에서 "+next+"로 바뀜");
           
currentState=next;
           
currentState.onEntry();
           
if(State.isFinalState(currentState)){
               
System.out.println("i'm final State");
            }
        }
else{
           
System.out.println(action+" state " +currentState
           
+"에서는 의미 없는 짓");
        }
    }
}

 

Main

public class Main {
   
public static void main(String[] args){
       
StateContext context = new StateContext();
       
context.processEvent(Action.EAT);
       
context.processEvent(Action.EAT);
       
context.processEvent(Action.GOTOBED);
       
context.processEvent(Action.DIGEST);
       
context.processEvent(Action.EAT);
       
context.processEvent(Action.GOTOBED);
       
context.processEvent(Action.DIGEST);
       
context.processEvent(Action.GOTOBED);
    }
}



결과




UML



Composite Pattern (컴포지트 패턴)

Composite Pattern

 


정의


Object group이 단일 object와 동일하게 다루는 것이다.


client들이 단일 object와 복합체(composition)들을 동일하게 다룬다.


 

용도


Clientobject들의 composition과 단일 object 사이 차이를 무시해야 할 때 사용한다


여러 개의 object들을 같은 방법으로 사용하거나


object들에게 비슷한 코드를 사용한다면 composite pattern을 생각해 볼 수 있다.


 

구조


1.    Composite


자식들을 다루는 메소드로 일반적으로 자식들에게 기능을 위임하여 component의 모든 method를 구현한다.


2.    Component


composite 하나를 포함하는, 자신을 포함한 모든 component들의 추상화로 composite에서 object들을 위한 interface를 제공한다


또한 선택적으로 component의 부모에 접근하기 위해 recursive structure interface를 구현하기도 한다.


3.    Leaf


composition에서 leaf 객체들을 나타내며, component의 모든 method들을 구현한다.


 

소스코드


Component

package CompositePattern;

public interface Component {
   
public void show();
}

 

composite

package CompositePattern;

import java.util.ArrayList;
import java.util.List;

public class Composite implements Component {

   
private List<Component> childComponents = new ArrayList<Component>();

   
public void add(Component component){
       
childComponents.add(component);
    }

   
public void remove(Component component){
       
childComponents.remove(component);
    }

   
@Override
    public void
show() {
       
childComponents.forEach(Component::show);
    }
}

 


 

Leaf

package CompositePattern;

public class Leaf implements Component {
   
private String name;
   
public Leaf(String name){
       
this.name=name;
    }
    
@Override
    public void
show() {
       
System.out.println(name);
    }
}

 

main

package CompositePattern;

public class Main {
   
public static void main(String[] args){
       
Leaf leaf1 = new Leaf("leaf 1");
       
Leaf leaf2 = new Leaf("leaf 2");
        
Leaf leaf3 = new Leaf("leaf 3");
       
Composite composite1 = new Composite();
       
composite1.add(leaf1);

       
Composite composite2 = new Composite();
       
composite2.add(leaf2);
       
composite2.add(leaf3);

       
composite1.add(composite2);
       
composite1.show();

       
System.out.println("remove 1");
       
composite1.remove(leaf1);
       
composite1.show();

       
System.out.println("remove composite 2");
       
composite1.remove(composite2);
       
composite1.show();

       
System.out.println("print composite 2");
       
composite2.show();
    }
}


결과화면




UML






Iterator Pattern (반복자 패턴)

Iterator Pattern


 

정의


collection의 구현을 드러내지 않으면서도 collection에 있는 모든 object에 대해 반복 작업을 할 수 있다.


Interface를 통해서 Array List, HashTable 등 서로 다른 집합 객체 구조에 대해서도 반복자를 구현할 수 있다.

 



장점


1.    리스트 등의 객체의 코드가 수정되어도 순회하는 코드에 영향이 없다.


2.    하나의 리스트 등 의 집합객체에 여러가지 순회방법을 정할 수 있다.


3.    Iteratoraggregate classinterface를 단순화



 

순서


1.    클래스 정의


2.    반복자 정의 (요소를 순서대로 검색해가는 API 결정)


3.    집합객체 정의 (Aggregate이 결정한 interface를 실제로 구현)


4.    Aggregate 정의 (리스트에 새로운 항목을 추가하거나 삭제)


5.    Iterator class를 재정의 하는 iterator (리스트상의 현재 위치를 조정)



 


소스코드

 

Aggregate

public interface Aggregate {

         public abstract Iterator iterator();

}

 

Food

public class Food {
         private String name;    
         public Food(String name){
                 this.name = name;
         }
         public String getName(){
                 return name;
         }
}

 

FoodBook

public class FoodBook implements Aggregate{
         private Food[] foods;
         private int last=0;
         public FoodBook(int maxsize){
                 this.foods = new Food[maxsize];
         }
         public Food getFoodAt(int index){
                 return foods[index];
         }
         public void appendFood(Food food){
                 this.foods[last] = food;
                 last++;
         }
         public int getLength(){
                 return last;
         }
         @Override
         public Iterator iterator() {
                 // TODO Auto-generated method stub
                 return new FoodBookIterator(this);
         }
}


Iterator

public interface Iterator {
         public abstract boolean hasNext();
         public abstract Object next();
}

 

FoodBookIterator

public class FoodBookIterator implements Iterator{
         private FoodBook foodBook;
         private int index;       
         public FoodBookIterator(FoodBook foodBook) {
                 // TODO Auto-generated constructor stub
                 this.foodBook=foodBook;
                 this.index=0;
         }
         @Override
         public boolean hasNext() {
                 return index < foodBook.getLength();
         }
         @Override
         public Object next() {
                 Food food = foodBook.getFoodAt(index);
                 index++;
                 return food;
         }
}

 

Main

public class Main {
         public static void main(String[] args) {
                 FoodBook foodBook = new FoodBook(4);             
                 foodBook.appendFood(new Food("kimchi"));
                 foodBook.appendFood(new Food("bulgogi"));
                 foodBook.appendFood(new Food("bibimbab"));
                 foodBook.appendFood(new Food("pizza"));
                 
                 Iterator iterator = foodBook.iterator();
                 
                 while(iterator.hasNext()){
                          Food food = (Food)iterator.next();
                          System.out.println(food.getName());
                 }
         }
}



UML


Facade Pattern (퍼사드 패턴)

Facade Pattern


 

정의


어떤 sub-systeminterface에 대한 통합된 interface를 제공하고 facade에서 고수준 interface를 정의하기 때문에 sub-system을 쉽게 사용할 수 있다.



 

장점


더욱 더 간단한 interface를 만들 수 있다는 것이다


또한 client부와 sub-system을 분리할 수도 있다


만약 clientfacade로 만들었다고 하면 interface가 달라졌을 때 client는 변경할 필요 없이 facade만 변경하면 된다


그리고 표면에 드러나 있는 interface를 사용하고 그 내부는 알 필요가 없다.


 

l  최소지식원칙(=Law of Demeter)


system design에 있어서 어떤 object든 그 object와 상호작용하는 class의 수에 주의해야 하며, object들과 어떤 식으로 상호작용하는지도 주의해야 한다는 원칙이다.


위 원칙을 지키기 위해서는 4 종류의 object method만 호출하면 되는데, 다음과 같다.


1.    객체 자체


2.    Methodparameter로 전달된 object


3.    method에서 생성하거나 instance를 만든 object


4.    object에 속하는 구성요소 (A has B)




Adapter Pattern, Facade Pattern, Decorator Pattern의 차이점


l  Adapter Pattern : interface를 다른 interface로 변환하는 것이다. Interface를 변경해서 client에서 필요로 하는 interface로 적응시키는 위한 용도로 호환성을 위한다.


l  Facade Pattern : interface를 간단하게 바꾸는 것으로, 어떤 sub-system에 대한 간단한 interface를 제공하기 위한 용도로 사용되며 간편할 때 사용한다.


l  Decorator Pattern : interface를 바꾸지 않고 기능만 추가하는 것으로 Object를 감싸서 새로운 기능을 추가하기 위해서 사용한다.



 

정리


1.    기존 class를 사용하려고 하는데 interface가 맞지 않으면 adapter pattern을 사용한다.


2.    interface 또는 여러 interface를 단순화 시키거나 통합시켜야 한다면 facade pattern을 사용한다.


3.    Adapter Patterninterfaceclient가 원하는 interface로 바꾸는 역할을 하고 Facade Pattern은 복잡한 sub-system과 분리하는 역할을 한다.


4.    Adapter Pattern은 다중 Adapter로 만들 수 있고 Façade Pattern은 한 sub-system에 여러 개 만들 수 있다.

'HeadFirstDesignPattern'에 해당되는 글 5건

1 →