728x90
어댑터 패턴이란?
호환성이 없는 인터페이스 때문에 함께 동작할 수 없는 클래스들이 함께 작동하도록 해주는 패턴이 어댑터 패턴
어댑터패턴 구조
public class First implements A {
private B b;
First(B b) {
this.b = b;
}
@Overrridng public display() {
b.func();
}
}
어댑터패턴 예시
public class AdapterPatternDemo {
public static void main(String[] args) {
AudioPlayer audioPlayer = new AudioPlayer();
audioPlayer.play("mp3", "beyond the horizon.mp3");
audioPlayer.play("mp4", "alone.mp4");
audioPlayer.play("vlc", "far far away.vlc");
}
}
public interface MediaPlayer {
public void play(String audioType, String fileName);
}
public class AudioPlayer implements MediaPlayer {
@Override
public void play(String audioType, String fileName) {
if(audioType.equalsIgnoreCase("mp3"))
System.out.println("Playing mp3 file. Name: " + fileName);
}
// 'vlc' 나 'mp4' 포맷은 MediaAdapter 로 처리한다.
else if(audioType.equalsIgnoreCase("vlc") || audioType.equalsIgnoreCase("mp4")){
mediaAdapter = new MediaAdapter(audioType);
mediaAdapter.play(audioType, fileName);
}
}
}
public interface AdvancedMediaPlayer {
public void playVlc(String fileName);
public void playMp4(String fileName);
}
public class VlcPlayer implements AdvancedMediaPlayer{
@Override
public void playVlc(String fileName) {
System.out.println("Playing vlc file. Name: "+ fileName);
}
@Override
public void playMp4(String fileName) {
}
}
public class Mp4Player implements AdvancedMediaPlayer{
@Override
public void playVlc(String fileName) {
//do nothing
}
@Override
public void playMp4(String fileName) {
System.out.println("Playing mp4 file. Name: "+ fileName);
}
}
public class MediaAdapter implements MediaPlayer {
AdvancedMediaPlayer advancedMusicPlayer;
public MediaAdapter(String audioType){
// 생성 시, vlc 인지 mp4 인지 구분.
if(audioType.equalsIgnoreCase("vlc") ){
advancedMusicPlayer = new VlcPlayer();
}else if (audioType.equalsIgnoreCase("mp4")){
advancedMusicPlayer = new Mp4Player();
}
}
@Override
public void play(String audioType, String fileName) {
// play 호출 시, 구체적인 각 플레이어의 메쏘드를 호출.
if(audioType.equalsIgnoreCase("vlc")){
advancedMusicPlayer.playVlc(fileName);
}
else if(audioType.equalsIgnoreCase("mp4")){
advancedMusicPlayer.playMp4(fileName);
}
}
}
'DESIGN PATTERN' 카테고리의 다른 글
[디자인패턴] 어댑터 패턴(Adapter Pattern)이란? - 개발자 배찌 (0) | 2022.04.11 |
---|---|
[디자인패턴] 책임 연쇄 패턴 (Chai- of-responsibility Pattern) - 개발자 배찌 (0) | 2022.04.11 |
[디자인패턴] 브릿지패턴(Bridge Pattern) 이란? - 개발자 배찌 (0) | 2022.04.07 |
[디자인패턴] 프록시패턴(proxy Pattern)과 데코레이터패턴(decorator Pattern) - 개발자 배찌 (0) | 2022.04.07 |
[디자인패턴] 스트래티지 패턴(Strategy Pattern)이란? - 개발자 배찌 (0) | 2022.02.03 |