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


Proxy Pattern (프록시 패턴)

Proxy Pattern


 

프록시


1.    원격프록시 : 원격객체에 대한 접근을 제어


2.    가상프록시 : 생성하기 힘든 자원(ex. Image)에 대한 접근을 제어


3.    보호프록시 : 접근권한이 필요한 자원에 대한 접근을 제어


 

사용 목적


실제 객체의 생성시간이 오래걸리는 경우 일을 분업하여 간단한 초기 작업을 프록시에서 하고


가장 중요한 마지막 작업에서 프록시객체는 실제 객체를 생성하고 위임한다.


 

특징


1.    프록시는 실제 서비스와 같은 이름의 메소드를 인터페이스를 사용하여 구현한다.


2.    프록시는 실제 서비스에 대한 참조 변수를 갖는다.


3.    대리자는 실제 서비스의 같은 이름을 가진 메소드를 호출하고 그 값을 클라이언트에게 돌려준다.


4.    대리자는 실제 서비스의 메소드 호출 전후에도 별도의 로직을 수행할 수 있다.



 

원격프록시


로컬 환경에 존재하며, 원격객체(JVM Heap에 있는 객체)에 대한 대변자 역할을 하는 객체


서로 다른 주소 공간에 있는 객체에 대해 마치 같은 주소 공간에 있는 것처럼 동작하게 만드는 패턴


 

가상프록시


꼭 필요로 하는 시점까지 객체의 생성을연기하고, 해당 객체가 생성된 것처럼 동작하도록 만들고 싶을 때 사용하는 패턴


 

보호프록시


객체에 대한 접근 권한을 제어하거나 객체마다 접근 권한을 달리하고 싶을 때 사용하는 패턴으로 


실객체에 대한 접근을 가로채어 중간에서 권한 점검을 수행


 

소스코드


인터페이스

public interface Image {
   
void display();
}

 

프록시

public class ProxyImage implements Image {
   
private RealImage realImage;
   
private String fileName;

   
public ProxyImage(String fileName){
       
this.fileName=fileName;
    }

   
@Override
    public void
display() {
       
if(realImage == null){
           
realImage = new RealImage(fileName);
        }
       
realImage.display();
    }
}

 

실제

public class RealImage implements Image {

   
private String fileName;

   
public RealImage(String fileName){
       
this.fileName=fileName;
       
loadFromDisk(fileName);
    }
   
private void loadFromDisk(String fileName){
       
System.out.println("Loading " + fileName);
    }
   
@Override
    public void
display() {
       
System.out.println("Displaying " + fileName);
    }
}

 

메인

public class Main {
   
public static void main(String[] args){
       
Image image = new ProxyImage("test.jpg");
       
image.display();
    }
}



결과화면




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


Template Method Pattern (템플릿메소드패턴)

Template Method Pattern

 


정의


상위 class에서 처리의 흐름을 제어하고, 하위class에서 처리의 내용을 구체화 한다


여러 class에서 공통되는 사항은 상위 추상 class에서 구현하고, 각각의 세부내용은 하위 class에서 구현한다


그 결과 코드의 중복을 줄이고, Refactoring에 유리한 패턴으로 상속을 통한 확장 개발 방법으로 Strategy Pattern과 함께 많이 사용되는 pattern이다.


 

Hook method


필수적이지 않은 부분으로 필요에 따라 선택적으로 sub-class에서 구현할 경우 사용한다


Abstract class에서 정의된 어떠한 행도 하지 않을 수 있고, sub-class의 공통된 동작을 할 수도 있다


또한, sub-class에서 hook method를 재정의 하여 사용하는 방법도 있다


Sub-class에 따라 algorithm에 원하는 내용을 추가할 수 있도록 하는 것이 hook-method의 존재 이유다.


 

요구사항


1.    멤버 함수들의 접근 범위 지정을 명확히 한다.


2.    가상함수, 일반함수로 선언 하는 것 에 대한 기준이 필요


3.    Virtual 함수의 수를 최소화한다.



l  Hollywood Principle

Sub-classupper-class에 구성요소로써 활용될 수 있지만, sub-class upper-class를 호출하여 자신을 호출하게 하면 안된다는 것이다


Template Method Pattern에서도 이러한 원칙을 따르고 있는데


설명을 더하면, abstract class에서는 sub-class에 있는 기능을 호출할 수 있지만


sub-class에서는 abstract-class template method를 호출하거나 수정할 수 없다는 것이다.

 


장점


상위위 class template method에서 알고리즘이 기술되어 있으므로,


하위 class에서는 알고리즘을 일일이 기술할 필요가 없다.


 

소스코드


상위클래스

public abstract class CaffeineBeverageWithHook {

         void prepareRecipe(){

                 boilWater();

                 brew();

                 pourInCup();

                 if(customerWantsCondiments()){

                          addCondiments();

                 }

         }

 

         abstract void brew();

         abstract void addCondiments();

 

         void boilWater(){

                 System.out.println("Boiling water");

         }

 

         void pourInCup(){

                 System.out.println("Pouring into cup");

         }

 

         boolean customerWantsCondiments(){

                 return true;

         }

}

 

하위클래스(coffee)

public class CoffeeWithHook extends CaffeineBeverageWithHook{
         @Override
         void brew() {
                 // TODO Auto-generated method stub
                 System.out.println("Dripping Coffee through filter");
         }
 
         @Override
         void addCondiments() {
                 // TODO Auto-generated method stub
                 System.out.println("Adding Sugar and Milk");
         }
         @Override
         public boolean customerWantsCondiments() {
                 // TODO Auto-generated method stub
                 String answer = getUserInput();
 
                 if(answer.toLowerCase().startsWith("y")){
                          return true;
                 }else{
                          return false;
                 }
         }
 
         private String getUserInput(){
                 String answer = null;
 
                 System.out.println("would you like milk&sugar with your coffee (y/n) ?");
                 BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
 
                 try {
                          answer = in.readLine();
                 } catch (Exception e) {
                          // TODO: handle exception1
                          System.err.println("IO error trying to read your answer");
                 }
 
                 if(answer==null){
                          return "no";
                 }
                 return answer;
         }
}

 

하위클래스(tea)

public class TeaWithHook extends CaffeineBeverageWithHook{
 
         @Override
         void brew() {
                 // TODO Auto-generated method stub
                 System.out.println("Steeping the tea");
         }
 
         @Override
         void addCondiments() {
                 // TODO Auto-generated method stub
                 System.out.println("Adding Lemon");
         }
         @Override
         public boolean customerWantsCondiments() {
                 // TODO Auto-generated method stub
                 String answer = getUserInput();
 
                 if(answer.toLowerCase().startsWith("y")){
                          return true;
                 }else{
                          return false;
                 }
         }
 
         private String getUserInput(){
                 String answer = null;
 
                 System.out.println("would you like lemon with your tea (y/n) ?");
                 BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
 
                 try {
                          answer = in.readLine();
                 } catch (Exception e) {
                          // TODO: handle exception1
                          System.err.println("IO error trying to read your answer");
                 }
 
                 if(answer==null){
                          return "no";
                 }
                 return answer;
         }
 
}

 

Main

public class BeverageTestDrive {
         public static void main(String[] args) {
                 TeaWithHook teaWithHook = new TeaWithHook();
                 CoffeeWithHook coffeeWithHook = new CoffeeWithHook();
                 
                 System.out.println("\n Making tea");
                 teaWithHook.prepareRecipe();
                 
                 System.out.println("\nMaking coffee");
                 coffeeWithHook.prepareRecipe();
         }
}

 

 

결과

Making tea

Boiling water

Steeping the tea

Pouring into cup

would you like lemon with your tea (y/n) ?

y

Adding Lemon

 

Making coffee

Boiling water

Dripping Coffee through filter

Pouring into cup

would you like milk &sugar with your coffee (y/n) ?

y

Adding Sugar and Milk



UML


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

Composite Pattern (컴포지트 패턴)  (0) 2017.09.15
Iterator Pattern (반복자 패턴)  (0) 2017.09.14
Facade Pattern (퍼사드 패턴)  (0) 2017.09.07
Adapter Pattern (어댑터 패턴)  (0) 2017.09.07
Command Pattern (커맨드 패턴)  (0) 2017.09.07

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에 여러 개 만들 수 있다.

Adapter Pattern (어댑터 패턴)

Adapters Pattern

 

정의 : class interface client에서 필요로 하는 다른 interface 변환한다. Adapter 이용하면 interface 호환성문제로 없는 class들을 연결해서 있다.




그림과 같이 Adapter 소스만 변경하여 Existing System Vender Class 연결해 준다.

 


1.    Class Adapter Pattern


A.    장점 : Adapter 전체를 다시 구현할 필요가 없다.


B.     단점 : 상속을 활용하기 때문에 유연성이 떨어진다.
(java
다중상속 -지원 X)


C.    Class Adapter에서는 다중 상속을 이용하기 때문에 JAVA에서는 사용할 없다 (간접적 다중상속 지원 à Interface 이용)

 

2.    Object Adapter Pattern


A.    장점 : Composition 사용하기 때문에 유연성이 뛰어나다.


B.     단점 : Adapter Class 대부분의 코드를 구현해야 하기 때문에 효율성이 떨어진다.

 


사용방법


1.    Client에서 Target Interface 사용하여 method 호출함으로써 adapter 요청을 한다.


2.    Adapter에서는 adapter interface 사용하여 요청을 adapter 대한 하나 이상의 메소드를 호출로 변환한다.


3.    Client에서는 호출 결과를 받긴 하지만 중간에 Adapter 역할이 있었는지 전혀 없다.



기존의 Duck interface

public interface Duck {

         public void quack();

         public void fly();

}

 

Duck interface implement하는 MallardDuck

public class MallardDuck implements Duck{
    @Override
    public void fly() {
     // TODO Auto-generated method stub
     System.out.println("Quack");
    }
 
    @Override
    public void quack() {
     // TODO Auto-generated method stub
     System.out.println("I'm flying");
    }
}

 

하지만 turkey 오고싶다. 그래서 interface 만들어준다.

public interface Turkey {
    public void gobble();
    public void fly();
}

 

, Duck interface 사용하기 위해 Adapter 사용한다.

public class TurkeyAdapter implements Duck{
    Turkey turkey;
     public TurkeyAdapter(Turkey turkey){
     this.turkey=turkey;
    }
     @Override
    public void quack() {
     turkey.gobble();
    }         
    @Override
    public void fly() {
     turkey.fly();
    }
}


 

Turkey interface implements 하는 WildTurkey

public class WildTurkey implements Turkey{
    @Override
    public void fly() {
     // TODO Auto-generated method stub
     System.out.println("Gobble gobble");
    }
    @Override
    public void gobble() {
     // TODO Auto-generated method stub
     System.out.println("I'm flying a short distance");
    }
}

 

Main 소스

public class DuckTestDrive {
    public static void main(String[] args) {
     MallardDuck duck = new MallardDuck();
     WildTurkey turkey = new WildTurkey();
     Duck turkeyAdapter = new TurkeyAdapter(turkey);
     
     System.out.println("The turkey says...");
     turkey.gobble();
     turkey.fly();
     System.out.println("The Duck says...");
     testDuck(duck);
     System.out.println("The TurkeyAdapter says...");
     testDuck(turkeyAdapter);
    }
    
    public static void testDuck(Duck duck){
     duck.quack();
     duck.fly();
    }
}

 

결과 화면

The turkey says...

I'm flying a short distance

Gobble gobble

The Duck says...

I'm flying

Quack

The TurkeyAdapter says...

I'm flying a short distance

Gobble gobble



UML



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();
}

 


구현


Singleton Pattern (싱글턴 패턴)

Singleton Pattern


정의


1.    Singleton Pattern은 해당 Classinstance가 하나만 만들어진다.


2.    어디서든 그 instance에 접근할 수 있게 한다.


3.    class에서 하나뿐인 instance를 관리하게 한다.


4.    Instance가 사용될 때 똑 같은 instance를 만드는 것이 아닌, 동일 instance를 사용하게끔 하는 것이다.

 

고전적인 Singleton Pattern

public class Singleton {
    private static Singleton uniqueInstance;
 
    private Singleton(){}
 
    public static Singleton getInstance() {
        if(uniqueInstance == null){
            uniqueInstance = new Singleton();
        }
        return uniqueInstance;
    }
}

전역변수로 instance를 생성하는데 private static 키워드를 사용한다.


Static이 붙은 class 변수는, 인스턴스화에 상관없이 사용할 수 있다.


하지만, private 접근 제어자로 인해

Singleton.uniqueInstance

와 같은 방법으로 접근할 수 없다


이 상태에서 private 키워드를 붙이는데 그러면 new 키워드를 사용할 수 없게 된다.


그 결과 외부 class가 위 classinstance를 가질 수 있는 방법은, getinstance() method를 사용하는 방법밖에 없다.


 하지만 위의 방법은 Multi-threading과 관련해서 문제가 생긴다


       그 이유는 thread getinstance() method를 호출하면 instance가 두 번 생길 수 있기 때문이다.


       이러한  문제를 방지하기 위해, getinstance() method를 동기화 시킨다.

public class Singleton {
    private static Singleton uniqueInstance;
    // 기타 인스턴스 변수
    private Singleton() {}
    //synchronized 키워드만 추가하면 
    // 두 스레드가 이 메소드를 동시에 실행시키는 일은 일어나지 않게 된다.
    public static synchronized Singleton getInstance() {
        if (uniqueInstance == null) {
            uniqueInstance = new Singleton();
        }
        return uniqueInstance;
    }
}


위와 같이 할 수 있는데 이 방법도 문제가 있다. 수 많은 thread들이 getinstance()

method를 호출하기 위해 동기화 하면 성능이 떨어진다.

이러한 문제를 방지하기 위해서 instance를 필요할 때 생성하는 것이 아니라, 처음부터 생성하는 방법이 있다.

public class Singleton {
    private static Singleton uniqueInstance = new Singleton();
 
    private Singleton() {}
 
    public static Singleton getInstance() {
        return uniqueInstance;
    }
}

위와 같이 하는 방법 외에도 DCL(Double-Checking Locking)을 사용하여 getinstance()에서 동기화되는 부분을 줄이는 방법이 있다.


DCL을 사용하면 instance가 생성되어 있는지 확인한 후, 생성이 되어있지 않을 때만 동기화를 할 수 있다


Volatile 키워드를 사용해서 multi-threading을 사용하더라도변수가 Singleton instance로 초기화 되는 과정이 올바르게 할 수 있다.

public class Singleton {
    private volatile static Singleton uniqueInstance;
 
    private Singleton() {}
 
    public static Singleton getInstance() {
        if (uniqueInstance == null) {
            //이렇게 하면 처음에만 동기화 된다
            synchronized (Singleton.class) {
                if (uniqueInstance == null) {
                    uniqueInstance = new Singleton();
                }
            }
        }
        return uniqueInstance;
    }
}


'SW/DesignPattern'에 해당되는 글 15건

1 2 →