μ΄λν° ν¨ν΄μ΄λ νΈνμ±μ΄ μλ μΈν°νμ΄μ€ λλ¬Έμ ν¨κ» λμν μ μλ ν΄λμ€λ€μ΄ ν¨κ» μλν μ μλλ‘ ν΄μ£Όλ ν¨ν΄μ΄λ€.
- κ΄κ³κ° μλ μΈν°νμ΄μ€λ₯Ό κ°μ΄ μ¬μ© κ°λ₯
- νλ‘κ·Έλ¨μ ν μ€νΈ νλλ° μ©μ΄
- ν΄λμ€ μ¬νμ©μ±μ΄ λμμ§
-
κ°μ²΄ μ΄λν° ν¨ν΄ - μμμ μ΄μ©ν μ΄λν° ν¨ν΄
-
ν΄λμ€ μ΄λν° ν¨ν΄ - μμμ μ΄μ©ν μ΄λν° ν¨ν΄
μμ(Inheritance)κ³Ό μμ(Delegation)μμ μμμ λν΄ μ΅μνμ§ μμ μ μλλ° μμμ΄λ λ€λ₯Έ ν΄λμ€μ κ°μ²΄λ₯Ό λ©€λ² λ³μλ‘ κ°λ ννμ ν΄λμ€μ΄λ€.
μλλ μ΄λ―Έμ§λ§ 보μ¬μ€ μ μλ λ·°μ΄κ° μλ€. μ¬κΈ°μ μꡬμ¬νμ μν΄ μ΄λ―Έμ§κ° μλ λμμλ λ³΄μ¬ μ£Όκ³ μΆλ€.
- Image ν΄λμ€λ Media μΈν°νμ΄μ€λ₯Ό μμνλ€.
- Video ν΄λμ€λ AdvancedMedia μΈν°νμ΄μ€λ₯Ό μμνλ€.
- νμ¬ κ°λ°λ μ½λλ₯Ό μμ ν μ μλ μν©μ΄λ€.
- μλ‘μ΄ Viewerλ₯Ό λ§λ€ μ μλ μν©μ΄λ€.
μ΄λ€ νμΌλ€μ μΆκ°νκ³ main()μ μ΄λ€ μ½λλ€μ΄ μΆκ° λλ©΄ μ’μ μ§ μκ°ν΄λ³΄μ.
Main.java
public class Main {
public static void main(String[] args) {
Media media = new Image("Monalisa");
Viewer viewer = new Viewer();
viewer.view(media);
}
}
Viewer.java
public class Viewer { // mediaμ show()λ₯Ό νΈμΆνλ μν
public void view(Media media){
media.show();
}
}
Media.java( Media interface )
public interface Media {
public void show();
}
Image.java
public class Image implements Media {
public String name;
public Image(String name) {
this.name = name;
}
@Override
public void show() {
System.out.println("Image :" + name);
}
}
- Video ν΄λμ€, AdvancedMedia μΈν°νμ΄μ€μ λν νμΌμ μΆκ°νλ€.
- Imageμ Videoλ interfaceκ° λ€λ₯΄κΈ° λλ¬Έμ Videoλ₯Ό λ°λ‘ Viewerμμ μ¬μ©ν μ μκΈ° λλ¬Έμ Adapterλ₯Ό μΆκ°ν΄μ€λ€.
AdvancedMedia.java( AdvancedMedia interface )
public interface AdvancedMedia {
public void play();
}
Video.java
public class Video implements AdvancedMedia {
public String name;
public Video(String name) {
this.name = name;
}
@Override
public void play() {
System.out.println("Video :" + name);
}
}
MediaAdapter.java
public class MediaAdapter implements Media {
public AdvancedMedia media; // μμ
public MediaAdapter(AdvancedMedia media) {
this.media = media;
}
@Override
public void show() {
media.play();
}
}
Main.java
public class Main {
public static void main(String[] args) {
Media media = new Image("Monalisa");
AdvancedMedia advancedMedia = new Video("IZONE M/V"); // μμν κ°μ²΄ μμ±
MediaAdapter mediaAdapter = new MediaAdapter(advancedMedia); // MediaAdapterμ advancedMedia μμ
Viewer viewer = new Viewer();
viewer.view(media);
viewer.view(mediaAdapter);
}
}
MediaAdapter.java
public class MediaAdapter extends Video implements Media { // μμ
public MediaAdapter(String name) {
super(name); // μμν Video ν΄λμ€ init
}
@Override
public void show() {
super.play(); // μμν Video ν΄λμ€μ play() μ€ν
}
}
Main.java
public class Main {
public static void main(String[] args) {
Media media = new Image("Monalisa");
MediaAdapter mediaAdapter = new MediaAdapter("IZONE M/V");
Viewer viewer = new Viewer();
viewer.view(media);
viewer.view(mediaAdapter);
}
}
μ΄λ€ Adapterλ₯Ό μ μ©ν΄λ κ²°κ³Όλ κ°κ² λμ¨λ€.
μ΄λ κ² μ΄λν° ν¨ν΄μ μ¬μ©νλ©΄ κΈ°μ‘΄ μμ€μ½λλ₯Ό μμ νμ§ μκ³ μλ‘μ΄ λλ λ§μΆκ³ μ νλ μΈν°νμ΄μ€μ λ§μΆ°μ λμκ°λ₯νκ² νλ€. κ·Έλ κΈ° λλ¬Έμ μμ€μ½λκ° μ’ λ κ°κ²°ν΄μ§κ³ μ μ§λ³΄μ λν μνν΄μ§λ€.