Page tree

Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

...

  • 메시지를 보내는 객체와 이를 받아 처리하는 객체들 간의 결합도를 없애기 위한 패턴입니다. 
    하나의 요청에 대한 처리가 반드시 한 객체에서만 되지 않고, 여러 객체에게 그 처리 기회를 전달합니다. 

Chain of Responsibility design pattern


장 단점

  • 객체 간의 행동적 결합도가 적어집니다. 


  • 객체에게 책임을 할당하는데 유연성을 높일 수 있습니다.


  • 메시지의 수신이 보장되지 않습니다.

UML


예제

Handlers are lined-up one by one, forming a chain

1)  홀수, 짝수 

Code Block
languagejava
themeRDark
firstline0
titleReceiver
linenumberstrue
collapsetrue
public abstract class Receiver {
	
	public String name;
	private Receiver next;
	
	public Receiver(String name) {
		this.name = name;
	}
	
	public Receiver setNext(Receiver next) {
		this.next = next;
		return next;
	}
	
	public final void support(int number) {
		if (resolve(number)) {
			System.out.println(number + ":"+name +"가 해결");
		} 
		
		else if (next != null) {
			next.support(number);
		} 
		
		else {
			System.out.println("어떤 객체도 처리하지 못함");
		}
		
	}
	
	
		
	public abstract boolean resolve(int number);
	
}

...

Code Block
languagejava
themeRDark
firstline0
titleClient
linenumberstrue
collapsetrue
public class Main {

	public static void main(String[] args) {
		Receiver odd_receiver = new Odd_Recevier("홀수 리시버");
		Receiver even_receiver = new Even_Receiver("짝수 리시버");
		
		odd_receiver.setNext(even_receiver);
		
		for (int i = 1; i <20; i++) {
			odd_receiver.support(i);
		}
		
		
	}
}


2)  동전 디스펜서

Code Block
languagejava
themeRDark
firstline0
titleReciever
linenumberstrue
collapsetrue
public class Currency {
	private int amount;
	
	public Currency(int amount) {
		this.amount = amount;
	}
	
	public int getAmount() {
		return this.amount;
	}
	
}

interface DispenseCain{
	void setNextChain(DispenseCain nextChain);
	void dispense(Currency cur);
}

...

Code Block
languagejava
themeRDark
firstline0
titleClient
linenumberstrue
collapsetrue
import java.util.Scanner;

public class Main {
	private DispenseCain c1;
	
	public Main() {
		this.c1 = new Dollar50Dispenser();
		DispenseCain c2 = new Dollar20Dispenser();
		DispenseCain c3 = new Dollar10Dispenser();
		
		c1.setNextChain(c2);
		c2.setNextChain(c3);
	}
	public static void main(String[] args) {
		Main pattern = new Main();
		
		Scanner input = null;
		
		while (true) {
			int amount = 0;
			System.out.println("값을 입력해주세요.");
			input = new Scanner(System.in);
			amount = input.nextInt();
			
			if (amount % 10 != 0) {
				System.out.println("10의 배수로 해주시죠.");
				continue;
			}
			
			
			pattern.c1.dispense(new Currency(amount));
		}

	}

}


참고


Talking with tech support can be hard



...