Java是一種廣泛使用的編程語言,它具有很強的可移植性和跨平臺性。在Java中,橋接模式和適配器模式都是非常有用的設計模式。
橋接模式允許將抽象和實現分離開來,使它們可以獨立地變化。它包括一個抽象部分和一個實現部分。抽象部分定義了高層次的接口,而實現部分則提供具體實現。橋接模式的目的是將兩部分解耦,從而使它們可以獨立地變化。
public abstract class Shape { protected Color color; public Shape(Color color) { this.color = color; } abstract void draw(); } public class Circle extends Shape { public Circle(Color color) { super(color); } void draw() { System.out.println("Draw circle with " + color); } } public interface Color { void fill(); } public class Red implements Color { void fill() { System.out.println("Fill with red"); } } public class Blue implements Color { void fill() { System.out.println("Fill with blue"); } } public static void main(String[] args) { Color red = new Red(); Shape circle = new Circle(red); circle.draw(); }
適配器模式用于將一個類的接口轉換為另一個類可以使用的接口。這是在兩個不兼容的接口之間進行橋接的一種方法。適配器模式有兩種:類適配器和對象適配器。類適配器使用多重繼承來適配接口,而對象適配器使用組合來適配接口。
public interface MediaPlayer { void play(String mediaType, String fileName); } public interface AdvancedMediaPlayer { void playVlc(String fileName); void playMp4(String fileName); } public class VlcPlayer implements AdvancedMediaPlayer { void playVlc(String fileName) { System.out.println("Playing vlc file: " + fileName); } void playMp4(String fileName) {} } public class Mp4Player implements AdvancedMediaPlayer { void playVlc(String fileName) {} void playMp4(String fileName) { System.out.println("Playing mp4 file: " + fileName); } } public class MediaAdapter implements MediaPlayer{ AdvancedMediaPlayer advancedMediaPlayer; void play(String mediaType, String fileName) { if(mediaType.equalsIgnoreCase("vlc")) { advancedMediaPlayer = new VlcPlayer(); advancedMediaPlayer.playVlc(fileName); } else if (mediaType.equalsIgnoreCase("mp4")) { advancedMediaPlayer = new Mp4Player(); advancedMediaPlayer.playMp4(fileName); } } } public class AudioPlayer implements MediaPlayer { MediaAdapter mediaAdapter; void play(String mediaType, String fileName) { if(mediaType.equalsIgnoreCase("mp3")) { System.out.println("Playing mp3 file: " + fileName); } else if(mediaType.equalsIgnoreCase("vlc") || mediaType.equalsIgnoreCase("mp4")) { mediaAdapter = new MediaAdapter(); mediaAdapter.play(mediaType, fileName); } else { System.out.println("Invalid media type"); } } } public static void main(String[] args) { MediaPlayer audioPlayer = new AudioPlayer(); audioPlayer.play("mp3", "mp3File.mp3"); audioPlayer.play("mp4", "mp4File.mp4"); audioPlayer.play("vlc", "vlcFile.vlc"); audioPlayer.play("mp5", "mp5File.mp5"); }
綜上所述,橋接模式和適配器模式都是非常有用的設計模式,可以幫助我們解決許多實際問題。