欢迎关注微信公众号:数据科学与艺术 作者WX:superhe199
设计模式是一种在软件设计中经常出现的解决问题的方案,它们提供了一种结构化的方法来处理常见的设计问题。下面我会简要介绍一些常见的设计模式,并提供一个案例分析和相关的源码示例。
案例分析:一个日志记录器的实现。只需要一个全局的日志记录器来记录系统日志。
源码示例:
public class Logger {
private static Logger instance;
private Logger() {
// 私有构造函数,防止外部实例化
}
public static synchronized Logger getInstance() {
if (instance == null) {
instance = new Logger();
}
return instance;
}
public void log(String message) {
// 实现日志记录逻辑
}
}
案例分析:一个电脑组装工厂,根据客户的需求创建不同配置的电脑。
源码示例:
public interface Computer {
void assemble();
}
public class GamingComputer implements Computer {
@Override
public void assemble() {
System.out.println("Assembling gaming computer.");
}
}
public class OfficeComputer implements Computer {
@Override
public void assemble() {
System.out.println("Assembling office computer.");
}
}
public class ComputerFactory {
public static Computer createComputer(String type) {
if (type.equalsIgnoreCase("gaming")) {
return new GamingComputer();
} else if (type.equalsIgnoreCase("office")) {
return new OfficeComputer();
} else {
throw new IllegalArgumentException("Invalid computer type.");
}
}
}
案例分析:一个气象站监测天气,并将天气数据通知给多个观察者。
源码示例:
public interface Observer {
void update(int temperature, int humidity);
}
public class WeatherStation {
private int temperature;
private int humidity;
private List<Observer> observers = new ArrayList<>();
public void addObserver(Observer observer) {
observers.add(observer);
}
public void removeObserver(Observer observer) {
observers.remove(observer);
}
public void notifyObservers() {
for (Observer observer : observers) {
observer.update(temperature, humidity);
}
}
public void setWeatherData(int temperature, int humidity) {
this.temperature = temperature;
this.humidity = humidity;
notifyObservers();
}
}
public class Display implements Observer {
@Override
public void update(int temperature, int humidity) {
System.out.println("Current temperature: " + temperature);
System.out.println("Current humidity: " + humidity);
}
}
public class WeatherApp {
public static void main(String[] args) {
WeatherStation weatherStation = new WeatherStation();
weatherStation.addObserver(new Display());
weatherStation.setWeatherData(25, 60);
}
}
以上是对几种常见的设计模式的简要介绍和示例代码分析。设计模式是软件工程中非常重要的概念,它们可以提高代码的可重用性、可维护性和可扩展性。