Adapter Pattern
Adapter Pattern에 대해 설명하는 페이지입니다.
Adapter Pattern
Tags
Design Pattern, Java
1. Introduction
- a.k.a
- Wrapper
- Purpose
- Permits classes with different interfaces to work together by creating a common object by which they may communicate and interact.
- Use When
- A class to be used doesn't meet interface requirements.
- Mechanism
- A client makes a request to the adapter by calling a method on it using the target interface.
- The adapter translates the request into one or more calls on the adaptee using the adaptee interface.
- The client receives the results of the call and never knows there is an adapter doing the translation.
- Motivation
- A toolkit or class library may have an interface which is incompatible with an application's interface we want to integrate.
- It's possible that we don't have access to the source code of the toolkit or library.
- Even if the source code is available, we may want to minimize the change.
- Summary
- Converts the interface of a class into another interface clients expect.
- Lets classes work together that couldn't otherwise because of incompatible interfaces.
- Class adapter and object adapter
2. How to Use (Example)
-
Target Interface
java1public interface Duck { 2 public void quack(); 3 public void fly(); 4} 5 6public class MallardDuck implements Duck { 7 public void quack() { 8 System.out.println("Quack."); 9 } 10 public void fly() { 11 System.out.println("I'm flying."); 12 } 13} -
Adaptee Interface
java1public interface Turkey { 2 public void gobble(); 3 public void fly(); 4} 5 6public class WildTurkey implements Turkey { 7 public void gobble() { 8 System.out.println("Gobble."); 9 } 10 public void fly() { 11 System.out.println("I'm flying."); 12 } 13} -
Object Adapter
java1public class TurkeyAdapter implements Duck { 2 Turkey turkey; // adaptee 3 public TurkeyAdapter(Turkey turkey) { 4 this.turkey = turkey; 5 } 6 public void quack() { 7 turkey.gobble(); 8 } 9 public void fly() { 10 for (int i = 0; i < 5; i++) { 11 turkey.fly(); 12 } 13 } 14}
