单例模式(Singleton)
场景:
在一个Web服务中,数据库连接池应当在整个应用生命周期中只创建一次,以减少资源消耗和提升性能。使用单例模式确保数据库连接池的唯一实例。
代码实现:
import java.sql.Connection;
import java.sql.SQLException;public class DatabaseConnectionPool {private static volatile DatabaseConnectionPool instance;private DatabaseConnectionPool() throws SQLException {// 初始化数据库连接池(省略具体实现)}public static DatabaseConnectionPool getInstance() throws SQLException {if (instance == null) {synchronized (DatabaseConnectionPool.class) {if (instance == null) {instance = new DatabaseConnectionPool();}}}return instance;}public Connection getConnection() {// 返回连接池中的连接(省略具体实现)return null;}
}// 使用示例
try {DatabaseConnectionPool pool1 = DatabaseConnectionPool.getInstance();DatabaseConnectionPool pool2 = DatabaseConnectionPool.getInstance();assert pool1 == pool2;
} catch (SQLException e) {e.printStackTrace();
}
观察者模式(Observer)
场景:
一个天气预报系统需要实时通知订阅用户最新的天气变化。使用观察者模式实现发布-订阅机制,使得天气服务端(Subject)能自动通知所有注册的观察者(Observer)>
代码实现:
import java.util.ArrayList;
import java.util.List;interface Observer {void update(WeatherData weatherData);
}interface Subject {void registerObserver(Observer observer);void removeObserver(Observer observer);void notifyObservers();
}class WeatherData implements Subject {private List<Observer> observers = new ArrayList<>();private float temperature;private float humidity;private float pressure;@Overridepublic void registerObserver(Observer observer) {observers.add