引言
设计模式是软件开发中常用的一种解决方案,它提供了一套经过测试的解决方案,帮助开发人员解决各种重复出现的问题。本文将介绍三种常用的设计模式:工厂模式、单例模式和观察者模式,并展示它们在实践中的具体应用。
工厂模式
工厂模式是一种创建型模式,它通过提供一个公共接口来创建对象,而无需显示指定其具体类型。在实践中,工厂模式常用于创建复杂对象或对象组合。
以创建一个图形对象为例。首先,定义一个接口 Shape,其中声明一个方法 draw。然后,创建三个具体的图形类 Circle、Square 和 Triangle,它们实现了 Shape 接口并实现了 draw 方法。最后,创建一个图形工厂类 ShapeFactory,根据不同的输入参数来创建相应的图形对象。
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 Triangle implements Shape {
@Override
public void draw() {
System.out.println("Drawing a triangle");
}
}
public class ShapeFactory {
public Shape getShape(String shapeType) {
if (shapeType == null) {
return null;
} else if (shapeType.equalsIgnoreCase("circle")) {
return new Circle();
} else if (shapeType.equalsIgnoreCase("square")) {
return new Square();
} else if (shapeType.equalsIgnoreCase("triangle")) {
return new Triangle();
}
return null;
}
}
使用工厂模式创建图形对象的示例代码如下:
public class Main {
public static void main(String[] args) {
ShapeFactory shapeFactory = new ShapeFactory();
Shape circle = shapeFactory.getShape("circle");
circle.draw();
Shape square = shapeFactory.getShape("square");
square.draw();
Shape triangle = shapeFactory.getShape("triangle");
triangle.draw();
}
}
运行上述示例代码,输出结果为:
Drawing a circle
Drawing a square
Drawing a triangle
单例模式
单例模式是一种创建型模式,它确保一个类只有一个实例,并提供一个全局访问点。在实践中,单例模式常用于管理共享资源或跟踪对象的状态。
下面以日志记录器为例,展示如何使用单例模式。
首先,定义一个单例类 Logger,将构造函数定义为私有,以防止外部直接实例化这个类。然后,声明一个静态实例变量 instance,并提供一个静态方法 getInstance 来获取该实例。在 getInstance 方法中,使用双重检查锁定来确保只有一个线程能够创建实例。
public class Logger {
private static volatile Logger instance;
private Logger() {
// 私有构造函数
}
public static Logger getInstance() {
if (instance == null) {
synchronized (Logger.class) {
if (instance == null) {
instance = new Logger();
}
}
}
return instance;
}
public void log(String message) {
System.out.println("Logging: " + message);
}
}
使用单例模式记录日志的示例代码如下:
public class Main {
public static void main(String[] args) {
Logger logger = Logger.getInstance();
logger.log("This is a log message");
}
}
运行上述示例代码,输出结果为:
Logging: This is a log message
观察者模式
观察者模式是一种行为型模式,它定义了一种一对多的依赖关系,让多个观察者对象同时监听一个主题对象。当主题对象发生变化时,它会自动通知所有的观察者对象。
以一个气象站为例,展示如何使用观察者模式。
首先,定义两个接口 Subject 和 Observer。Subject 接口声明了注册、注销和通知观察者的方法。Observer 接口声明了更新观察者状态的方法。然后,创建具体的气象站类 WeatherStation,实现 Subject 接口,它包含一个观察者列表和一个数据状态。最后,创建观察者类 Display,实现 Observer 接口,当接收到更新通知时,显示气象站的数据状态。
import java.util.ArrayList;
import java.util.List;
public interface Subject {
void registerObserver(Observer observer);
void removeObserver(Observer observer);
void notifyObservers();
}
public interface Observer {
void update(float temperature, float humidity, float pressure);
}
public class WeatherStation implements Subject {
private List<Observer> observers;
private float temperature;
private float humidity;
private float pressure;
public WeatherStation() {
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() {
for (Observer observer : observers) {
observer.update(temperature, humidity, pressure);
}
}
public void setMeasurements(float temperature, float humidity, float pressure) {
this.temperature = temperature;
this.humidity = humidity;
this.pressure = pressure;
notifyObservers();
}
}
public class Display implements Observer {
@Override
public void update(float temperature, float humidity, float pressure) {
System.out.println("Temperature: " + temperature);
System.out.println("Humidity: " + humidity);
System.out.println("Pressure: " + pressure);
}
}
使用观察者模式实现气象站的示例代码如下:
public class Main {
public static void main(String[] args) {
WeatherStation weatherStation = new WeatherStation();
Display display = new Display();
weatherStation.registerObserver(display);
weatherStation.setMeasurements(25.3f, 62.8f, 1023.5f);
}
}
运行上述示例代码,输出结果为:
Temperature: 25.3
Humidity: 62.8
Pressure: 1023.5
结论
在本文中,我们介绍了三种常用的设计模式:工厂模式、单例模式和观察者模式,并展示了它们在实践中的具体应用。工厂模式用于创建对象,单例模式确保一个类只有一个实例,观察者模式用于实现一对多的依赖关系。熟练使用这些设计模式将有助于提高代码的可维护性和可扩展性。
本文来自极简博客,作者:琉璃若梦,转载请注明原文链接:设计模式实践:工厂模式、单例模式、观察者模式