Transcript Ch09

Ch.9 Bridge Pattern
Dislpay
-impl
+open
+print
+close
DisplayImpl
+rawOpen
+rawPrint
+rawClose
+display
CountDisplay
+multiDisplay
StringDisplayImpl
+rawOpen
+rawPrint
+rawClose
기능적 class 계층
장덕성
구현적 class 계층
계명대학교 컴퓨터공학과 정보공학실험실
Ch.9 Bridge Pattern
▌Display Class
public class Display {
private DisplayImpl impl;
public Display(DisplayImpl impl) { // 구현한 class의 instance를 impl로 받음
this.impl = impl;
}
public void open() {
impl.rawOpen(); // rawOpen()의 구현을 stringDisplayImpl에서 처리
}
public void print() {
impl.rawPrint();
}
public void close() {
impl.rawClose();
}
public final void display() {
open(); print();
close();
}
}
장덕성
계명대학교 컴퓨터공학과 정보공학실험실
Ch.9 Bridge Pattern
▌CountDisplay Class
public class CountDisplay extends Display {
public CountDisplay(DisplayImpl impl) { // 상위 class와 같이
// bridge 역할을 하는 field
super(impl);
}
public void multiDisplay(int times){ // open()과 close()로
// 틀을 만들고
// string을 times 만큼 출력
open();
for (int i = 0; I < times; i++) {
print();
}
close();
}
▌DisplayImpl Class
public abstract class DisplayImpl {
public abstract void rawOpen();
public abstract void rawPrint();
public abstract void rawClose();
}
장덕성
계명대학교 컴퓨터공학과 정보공학실험실
Ch.9 Bridge Pattern
▌ StringDisplayImpl Class
public class StringDisplayImpl extends DisplayImpl {
private String string;
// 표시해야할 문자열
private int width;
// 바이트 단위로 계산한 문자열의 "길이"
StringDisplayImpl(String string) {
this.string = string;
this.width = string.getBytes().length;
}
public void rawOpen() {
printLine();
}
public void rawPrint() {
System.out.println("|" + string + "|");
// 앞뒤에 "|"를 붙여서 표시
}
public void rawClose() {
printLine();
}
private void printLine() { // 모서리에 ‘+’와 width 개의 ‘-’를 표시
System.out.print("+");
for (int i = 0; i < width; i++) {
System.out.print("-");
}
public
System.out.println("+");
}
}
장덕성
계명대학교 컴퓨터공학과 정보공학실험실
Ch.9 Bridge Pattern
▌Main Class
public class Main {
public static void main(String[] args) {
Display d1 = new Display(new
StringDisplayImpl("Hello, Korea."));
Display d2 = new CountDisplay(new
StringDisplayImpl("Hello, World."));
CountDisplay d3 = new CountDisplay(new
StringDisplayImpl("Hello, Universe."));
d1.display();
d2.display();
d3.display();
d3.multiDisplay(5);
}
}
장덕성
계명대학교 컴퓨터공학과 정보공학실험실