요청을 처리하는 동일 인터페이스 객체들을
체인 형태로 연결해놓는 패턴
클라이언트로부터의 요청을 처리할 수 있는 처리객체를 집합(Chain)으로 만들어 부여함으로 결합을 느슨하기 위해 만들어진 디자인 패턴
적용 경우
Currency.class
public class Currency {
private int amount;
public Currency(int amt) {
this.amount=amt;
}
public int getAmount() {
return this.amount;
}
}
DispenseChain class
public interface DispenseChain {
void setNextChain(DispenseChain nextChain);
void dispense(Currency cur);
}
setNextChain()
을 통해 다음 체인을 설정하고 dispense()
을 통해 기능을 동작한다Won1Dispenser.class
public class Won1Dispenser implements DispenseChain{
private DispenseChain chain;
@Override
public void setNextChain(DispenseChain nextChain) {
this.chain=nextChain;
}
@Override
public void dispense(Currency cur) {
int num=cur.getAmount()/1;
System.out.println("Dispensing " +num+" 1₩ note");
}
}
Won10Dispenser.class
public class Won10Dispenser implements DispenseChain{
private DispenseChain chain;
@Override
public void setNextChain(DispenseChain nextChain) {
this.chain=nextChain;
}
@Override
public void dispense(Currency cur) {
if(cur.getAmount()>=10){
int num=cur.getAmount()/10;
int remainder=cur.getAmount()%10;
System.out.println("Dispensing " +num+" 10₩ note");
if(remainder!=0) this.chain.dispense(new Currency(remainder));
}
else this.chain.dispense(cur);
}
}
Won100Dispenser.class
public class Won100Dispenser implements DispenseChain{
private DispenseChain chain;
@Override
public void setNextChain(DispenseChain nextChain) {
this.chain=nextChain;
}
@Override
public void dispense(Currency cur) {
if(cur.getAmount()>=100){
int num=cur.getAmount()/100;
int remainder=cur.getAmount()%100;
System.out.println("Dispensing " +num+" 100₩ note");
if(remainder!=0) this.chain.dispense(new Currency(remainder));
}
else this.chain.dispense(cur);
}
}
DispenseChain
을 통해 다음 chain을 저장하고 dispense()
끝난 뒤, 잔여 작업이 남았으면, 다음 체인으로 전달한다Main.class
public static void main(String[] args) {
DispenseChain c1 = new Won100Dispenser();
DispenseChain c2 = new Won10Dispenser();
DispenseChain c3 = new Won1Dispenser();
c1.setNextChain(c2);
c2.setNextChain(c3);
c1.dispense(new Currency(378));
}
>Dispensing 3 100₩ note
>Dispensing 7 10₩ note
>Dispensing 8 1₩ note
참조: