Archive for the ‘ design pattern ’ Category

Adapter 패턴

Adapter 패턴에는 다음과 같이 두 가지 종류가 있습니다.

  • 클래스에 의한 Adapter 패턴(상속을 사용한 Adapter 패턴)
  • 인스턴스에 의한 Adapter 패턴(위임을 사용한 Adapter 패턴)

Adapter 패턴의 등장인물

Target(대상)의 역할

지금 필요한 메소드를 결정합니다.

Client(의뢰자)의 역할

Target 역할의 메소드를 사용해서 일을 합니다. 예제 프로그램에서 Main클래스가 이 역할.

Adaptee(개조되는 쪽)의 역할

Adapt-er(개조하는 쪽)이 아니고 Adapt-ee(개조되는 쪽)입니다. Adaptee는 이미 준비되어 있는 메소드를 가지고 있는 역할을 합니다.

Adapter의 역할

Adapter 패턴의 주인공입니다. Adpater 역할의 메소드를 사용해서 어떻게든 Target 역할을 만족시키기 위한 것이 Adapter 패턴의 목적이며, Adapter 역할의 임무입니다.

클래스에 의한 Adpater 패턴의 경우에는 Adapter의 역할을 ‘상속’ 을 사용한 Adaptee의 역할을 이용하지만, 인스턴스에 의한 Adapter 패턴의 경우에는 ‘위임’ 을 사용한 Adaptee의 역할을 이용합니다.

어떤 경우에 사용하는 것일까?

Adapter 패턴은 기존의 클래스를 개조해서 필요한 클래스를 만듭니다. 이 패턴으로 필요한 메소드를 발빠르게 만들 수 있습니다. 만약 버그가 발생해도 기존의 클래스(Adaptee의 역할)에는 버그가 없으므로 Adapter 역할의 클래스를 중점적으로 조사하면 되고, 프로그램 검사도 상당히 쉬워집니다.

Iterator 패턴

Iterator 패턴이란, 무엇인가 많이 모여있는 것들을 순서대로 지정하면서 전체를 검색하는 처리를 실행하기 위한 것이다. iterator는 무엇인가를 ‘반복한다’ 라는 의미이며, 반복자라고도 한다.

Aggregate 인터페이스

Aggregate 인터페이스는 요소들이 나열되어 있는 ‘집합체’를 나타낸다. 이 인터페이스를 구현하고 있는 클래스는 배열과 같은 무엇인가가 많이 모여 있다.

public interface Aggregate {
    public abstract Iterator iterator();
}

Iterator 인터페이스

Iterator 인터페이스는 요소를 하나씩 나열하면서 루프 변수와 같은 역할을 수행한다.

‘다음 요소’ 가 존재하는지를 조사하기 위한 boolean형 hasNext 메소드

‘다음 요소’ 를 얻기 위한 Object형 next 메소드

public interface Iterator {
    public abstract boolean hasNext();
    public abstract Object next();
}

Book 클래스

  • 문자열을 저장하는 name
  • 문자열을 받는 생성자
  • 책 이름을 반환하는 getName 메소드
public class Book {
	private String name;
	public Book(String name){
		this.name = name;
	}
	public String getName(){
		return name;
	}
}

BookShelf 클래스

Aggregate 인터페이스를 구현

public class BookShelf implements Aggregate {
	private Book[] books;
	private int last = 0;
	public BookShelf(int maxsize){
		this.books = new Book[maxsize];
	}
	public Book getBookAt(int index){
		return books[index];
	}
	public void appendBook(Book book){
		this.books[last] = book;
		last++;
	}
	public int getLength(){
		return last;
	}
	public Iterator iterator(){
		return new BookShelfIterator(this);
	}
}

BookShelfIterator 클래스

public class BookShelfIterator implements Iterator{
	private BookShelf bookShelf;
	private int index;

	public BookShelfIterator(BookShelf bookShelf){
		this.bookShelf = bookShelf;
		this.index = 0;
	}
	public boolean hasNext(){
		if(index < bookShelf.getLength()){
			return true;
		}
		else{
			return false;
		}
	}
	public Object next(){
		Book book = bookShelf.getBookAt(index);
		index++;
		return book;
	}
}

Main 클래스

public class Main {
	public static void main(String[] args) {
		BookShelf bookShelf = new BookShelf(4);		// index = 4
		bookShelf.appendBook(new Book("Around the World in 80 Days"));
		bookShelf.appendBook(new Book("Bible"));
		bookShelf.appendBook(new Book("Cinderella"));
		bookShelf.appendBook(new Book("Daddy-Long-Legs"));

		Iterator it = bookShelf.iterator();

		/*
		 * while 루프가 돌아가고, 루프 내에서 it.next()에 의해
		 * 책을 한 권씩 조사하게 된다.
		 */
		while(it.hasNext()){
			Book book = (Book)it.next();
			System.out.println(book.getName());
		}
	}
}

Iterator 패턴의 등장인물

Iterator(반복자)의 역할 : 요소를 순서대로 검색해가는 인터페이스(API)를 결정

ConcreteIterator(구체적인 반복자)의 역할 : Iterator가 결정한 인터페이스(API)를 실제로 구현

Aggregate(집합체)의 역할 : Iterator 역할을 만들어내는 인터페이스(API)를 결정

ConcreteAggregate(구체적인 집합체)의 역할 : Aggregate 역할이 결정한 인터페이스(API)를 실제로 구현하는 일