Pattern

adapter pattern

파이팅야 2008. 4. 18. 13:15

Adapter Pattern은 특정 클래스의 인터페이스를 클라이언트가 기대하는 다른 인터페이스로 전환시킨다.

인터페이스가 호환되지 않아 상호작용할 수 없는 경우에, Adapter를 이용하여 클래스 사이의 인터페이스의 호환성을 보장 가능함.

 (Convert the interface of a class into another interface clients expect. Adapter lets classes work together that couldn't otherwise because of incompatible interfaces.)

- 새로운 인터페이스로 클래스를 감싸게 되기 때문에 Wrapper 패턴이라고도 함.

- Bridge 패턴은 Object Adapter와 유사한 구조를 갖고 있지만, 서로 의도가 다르다. Adapter는 존재하고 있는 객체에 대한 인터페이스를 바꾸기 위한 의도를 갖지만, Bridge는 인터페이스를 해당 구현체(implementation)분리하기 위한 의도를 띈다

- 아래와 같이 적용하는 패턴의 방법은 2가지가 있다.

1) Class Adapter pattern 

다중상속으로 구현하는 방법. Java에서는 다중상속 안됨. C++에서 사용하면 됨


2) Object Adapter pattern 

Object를 이용해서 구현하는 방법.

(예로 Adapter의 생성자에서 adaptee를 생성해서 Operation1()에서 adaptee.Operation2()를 호출함)

 

ㅇ. 구현 예


ㅇ. 소스

public abstract class Unit {
abstract void move();
abstract void attack();
}
public class Marine extends Unit {
void attack() {
System.out.println("탕탕탕(마린 공격)");
}
void move() {
System.out.println("튀튀 ~~~ (마린 이동)");
}
}
public class Hydralisk extends Unit {
void attack() {
System.out.println("툇!툇!(히드라 침뱉는 소리)");
}
void move() {
System.out.println("엉금 엉금 (히드라 이동)");
}
}
public class Ghost extends Unit {
public Ninja ninja = null;
public Ghost() {
this.ninja = new Ninja();
}
void attack() {
this.ninja.cut();
}
void move() {
this.ninja.walk();
}
}
public class Battlecruiser extends Unit {
public Airwolf airwolf = null;
public Battlecruiser() {
this.airwolf = new Airwolf();
}
void attack() {
this.airwolf.shoot();
}
void move() {
this.airwolf.fly();
}
}
public class Ninja {
public void walk() {
System.out.println("걷기");
}
public void cut() {
System.out.println("자르기");
}
}
public class Airwolf {
public void fly() {
System.out.println("날기");
}
public void shoot() {
System.out.println("총쏘기");
}
}
public class Client {
public static void main(String[] args) {
System.out.println("-- Ghost --");
Unit ghost = new Ghost();
ghost.move();
ghost.attack();
System.out.println("-- Battlecruiser --");
Unit battlecruiser = new Battlecruiser();
battlecruiser.move();
battlecruiser.attack();
}
}

-- Ghost --
걷기
자르기
-- Battlecruiser --
날기
총쏘기

ㅇ. 참고

- wikipedia : 

http://en.wikipedia.org/wiki/Adapter_pattern

- 위키피디아 : 

http://ko.wikipedia.org/wiki/%EC%96%B4%EB%8C%91%ED%84%B0_%ED%8C%A8%ED%84%B4