어댑터 패턴은 한 인터페이스를 사용자가 사용하고자 하는 다른 인터페이스로 변환하는 패턴이다.
왜 사용하는가?
호환되지 않는 인터페이스를 사용하는 클라이언트를 그대로 활용할수 있다.
이렇게 함으로써 클라이언트와 구현된 인터페이스를 분리시킬수 있으며, 향후 인터페이스가 바뀌더라도 그 변경 내역
은 어댑터에 캡슐화 되기 때문에 클라이언트는 바뀔 필요가 없어진다.
어댑터에는 두종류가 있다.
하나는. 객체 어댑터
다른 하나는. 클래스 어댑터
클래스 어댑터 패턴을 쓰려면 다중 상속이 필요한데, 자바에서는 다중 상속이 불가능하다.
구조 (클래스)

구조(객체)

예시 코드에서는 만약 우리가 유저를 로그인 시키는 인터페이스가 있다고 쳐보자.
근데 여기서 구글유저를 로그인 시키고싶은데 구글유저의 로그인은 원래 유저의 로그인방법과 다를 것이다.
이때 어댑터를 이용해 구글유저가 로그인시키는 기준 인터페이스를 사용할 수 있도록 해보자
한눈으로 보자면
DefaultInterface -> Target
GoogleUsersAPI -> Adaptee
ObjectAdapter, ClassAdapter-> Adapter
이렇게 될 것이다.
DefaultInterface (타겟)
//This is the "target" - the interface that the client wants to use
public interface DefaultInterface
{
void Login(string username, string password);
DefaultUser GetUser();
}
GoogleUsersAPI(어댑티)
public class GoogleUsersAPI
{
//This is the "adaptee" - the class that we need an adapter to adapt to the target (DefaultInterface)
public GoogleUser LoginWithEmailAndPassword(string username, string password)
{
// run some http querying maybe...
// could be complex and we want to isolate this from the client
if (username == "bsmith" && password == "password")
{
return new GoogleUser("Bob", "bob@gmail.ca");
}
throw new Exception("I'm Google: bad username/password");
}
}
클래스 어댑터
public class ClassAdapter : GoogleUsersAPI, DefaultInterface
{
private DefaultUser defaultUser;
public DefaultUser GetUser()
{
return defaultUser;
}
public void Login(string username, string password)
{
try
{
// need to call API method to log in
GoogleUser user = LoginWithEmailAndPassword(username, password);
// need to change the Google user into an Auth user
defaultUser = new DefaultUser(user.GetName(), user.GetEmail());
}
catch (Exception e)
{
Console.WriteLine("Error: " + e.Message);
}
}
}
객체 어댑터 -> 자바에선 이걸 사용해야 할 것이다
public class ObjectAdapter : DefaultInterface
{
private GoogleUsersAPI googleAPI;
private DefaultUser defaultUser;
public ObjectAdapter()
{
googleAPI = new GoogleUsersAPI();
}
public DefaultUser GetUser()
{
return defaultUser;
}
public void Login(string username, string password)
{
try
{
// need to call API method to log in
GoogleUser user = googleAPI.LoginWithEmailAndPassword(username, password);
// need to change the Google user into an Auth user
defaultUser = new DefaultUser(user.GetName(), user.GetEmail());
}
catch (Exception e)
{
Console.WriteLine("Error: " + e.Message);
}
}
}
메인프로그램
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Username: ");
string username = Console.ReadLine();
Console.WriteLine("Password: ");
string password = Console.ReadLine();
DefaultInterface loginInterface = new ObjectAdapter();
loginInterface.Login(username, password);
DefaultUser user = loginInterface.GetUser();
if (user != null)
{
Console.WriteLine("Logged in - email is " + user.GetEmail());
}
else
{
Console.WriteLine("Login failed");
}
}
}
결과
Username:
bsmith
Password:
password
Logged in - email is bob@gmail.ca
'개인공부 > 소프트웨어 개발 패턴' 카테고리의 다른 글
| (구조패턴)Decorator 데코레이터 패턴 (1) | 2024.10.18 |
|---|---|
| (구조패턴) Bridge 브릿지 패턴 (0) | 2024.10.17 |
| (구조패턴) Composite 컴포짓 패턴 (0) | 2024.10.16 |
| (생성패턴) Builder 빌더 디자인 패턴 (0) | 2024.10.16 |
| (생성패턴) Abstract Factory 추상 팩토리 패턴 (1) | 2024.10.15 |