设计模式是软件开发中常用的解决方案,可以帮助我们构建灵活可扩展的应用程序。本文将深入探讨Java的七大经典设计模式,并提供相关示例代码。
一、单例模式
单例模式确保一个类只有一个实例,并提供全局访问点。以下是一个简单的单例模式示例代码:
public class Singleton {
private static Singleton instance;
private Singleton() {}
public static Singleton getInstance() {
if (instance == null) {
instance = new Singleton();
}
return instance;
}
}
二、工厂模式
工厂模式通过工厂类创建对象,将对象的实例化过程封装起来。以下是一个简单的工厂模式示例代码:
public interface Shape {
void draw();
}
public class Circle implements Shape {
@Override
public void draw() {
System.out.println("Drawing a circle");
}
}
public class Square implements Shape {
@Override
public void draw() {
System.out.println("Drawing a square");
}
}
public class ShapeFactory {
public Shape createShape(String type) {
if ("circle".equalsIgnoreCase(type)) {
return new Circle();
} else if ("square".equalsIgnoreCase(type)) {
return new Square();
}
return null;
}
}
三、观察者模式
观察者模式定义了一种一对多的依赖关系,当一个对象状态发生改变时,其所有依赖者会收到通知。以下是一个简单的观察者模式示例代码:
public interface Observer {
void update(String message);
}
public class ConcreteObserver implements Observer {
@Override
public void update(String message) {
System.out.println("Received message: " + message);
}
}
public interface Subject {
void registerObserver(Observer observer);
void removeObserver(Observer observer);
void notifyObservers(String message);
}
public class ConcreteSubject implements Subject {
private List<Observer> observers = new ArrayList<>();
@Override
public void registerObserver(Observer observer) {
observers.add(observer);
}
@Override
public void removeObserver(Observer observer) {
observers.remove(observer);
}
@Override
public void notifyObservers(String message) {
for (Observer observer : observers) {
observer.update(message);
}
}
}
四、适配器模式
适配器模式将一个类的接口转换成客户端所期望的另一个接口。以下是一个简单的适配器模式示例代码:
public interface MediaPlayer {
void play(String mediaType, String filename);
}
public class AudioPlayer implements MediaPlayer {
private MediaAdapter mediaAdapter;
@Override
public void play(String mediaType, String filename) {
if ("mp3".equalsIgnoreCase(mediaType)) {
System.out.println("Playing MP3 file: " + filename);
} else if ("vlc".equalsIgnoreCase(mediaType) || "mp4".equalsIgnoreCase(mediaType)) {
mediaAdapter = new MediaAdapter(mediaType);
mediaAdapter.play(mediaType, filename);
} else {
System.out.println("Invalid media. " + mediaType + " format not supported");
}
}
}
public class MediaAdapter implements MediaPlayer {
private AdvancedMediaPlayer advancedMediaPlayer;
public MediaAdapter(String mediaType) {
if ("vlc".equalsIgnoreCase(mediaType)) {
advancedMediaPlayer = new VlcPlayer();
} else if ("mp4".equalsIgnoreCase(mediaType)) {
advancedMediaPlayer = new Mp4Player();
}
}
@Override
public void play(String mediaType, String filename) {
if ("vlc".equalsIgnoreCase(mediaType)) {
advancedMediaPlayer.playVlc(filename);
} else if ("mp4".equalsIgnoreCase(mediaType)) {
advancedMediaPlayer.playMp4(filename);
}
}
}
标签:Java,String,observer,void,七大,mediaType,equalsIgnoreCase,源码,public
From: https://blog.51cto.com/u_11543122/8720248