자바
템플릿 메소드 예제,자바강좌,JAVA Template
Method,JAVA교육강좌학원,오라클자바커뮤니티자바교육,오엔제이프로그래밍실무JAVA교육
/*
*
Template Method를 구현하고, Template Method에서
*
사용되는 추상메소드를 선언
*/
public
abstract class AbstractDisplay {
public abstract void open();
public abstract void print();
public abstract void close();
public final void display() {
open();
for (int i = 0; i < 5; i++) {
print();
}
close();
}
}
/*
* 추상클래스인 AbstractDisplay 클래스의
* open, print, close 메소드를 구현
*/
public class GreetingDisplay extends AbstractDisplay {
private String s;
public GreetingDisplay(String s) {
this.s = s;
}
public void open() {
System.out.println("hello " + s);
}
public void print() {
System.out.println("your name is " + s);
}
public void close() {
System.out.println("bye~ " + s);
}
}
/*
* open, print, close 메소드 구현
*/
public class StringDisplay extends AbstractDisplay {
private String string;
private int width;
public StringDisplay(String string) {
this.string = string;
this.width = string.getBytes().length;
}
public void open() {
printLine();
}
public void print() {
System.out.println("|" + string + "|");
}
public void close() {
printLine();
}
private void printLine() {
System.out.print("+");
for (int i = 0; i < width; i++) {
System.out.print("-");
}
System.out.println("+");
}
}
public class Main {
public static void main(String[] args) {
AbstractDisplay d1 = new GreetingDisplay("이종철");
AbstractDisplay d2 = new StringDisplay("Hello, world.");
AbstractDisplay d3 = new StringDisplay("안녕하세요~");
d1.display();
d2.display();
d3.display();
}
}
댓글 없음:
댓글 쓰기