java几种常用设计模式简单示例
时间: 2023-07-11 22:17:35 浏览: 157
好的,我来为您简单介绍几种常用的Java设计模式,并附上示例代码。
1. 工厂模式(Factory Pattern)
定义:工厂模式是一种创建型设计模式,它提供了一种创建对象的最佳方式,而无需向客户端暴露创建逻辑,并且是通过使用一个公共接口来指向新创建的对象。
示例代码:假设我们有一个形状(Shape)接口,有三个不同的实现:圆形(Circle)、矩形(Rectangle)和正方形(Square)。我们可以使用工厂模式创建这些形状。
```
public interface Shape {
void draw();
}
public class Circle implements Shape {
@Override
public void draw() {
System.out.println("Drawing Circle");
}
}
public class Rectangle implements Shape {
@Override
public void draw() {
System.out.println("Drawing Rectangle");
}
}
public class Square implements Shape {
@Override
public void draw() {
System.out.println("Drawing Square");
}
}
public class ShapeFactory {
public Shape getShape(String shapeType) {
if (shapeType == null) {
return null;
}
if (shapeType.equalsIgnoreCase("CIRCLE")) {
return new Circle();
} else if (shapeType.equalsIgnoreCase("RECTANGLE")) {
return new Rectangle();
} else if (shapeType.equalsIgnoreCase("SQUARE")) {
return new Square();
}
return null;
}
}
```
我们可以使用ShapeFactory类来获取不同类型的形状对象:
```
ShapeFactory shapeFactory = new ShapeFactory();
Shape circle = shapeFactory.getShape("CIRCLE");
circle.draw();
Shape rectangle = shapeFactory.getShape("RECTANGLE");
rectangle.draw();
Shape square = shapeFactory.getShape("SQUARE");
square.draw();
```
2. 单例模式(Singleton Pattern)
定义:单例模式是一种创建型设计模式,它保证一个类只有一个实例,并提供一个全局访问点。
示例代码:假设我们有一个Settings类,用于存储应用程序的设置信息。我们可以使用单例模式确保只有一个Settings实例,以便在整个应用程序中共享设置。
```
public class Settings {
private static Settings instance = new Settings();
private Settings() {}
public static Settings getInstance() {
return instance;
}
public void setSetting(String key, String value) {
// ...
}
public String getSetting(String key) {
// ...
return null;
}
}
```
我们可以通过Settings.getInstance()方法获取Settings的唯一实例:
```
Settings settings = Settings.getInstance();
settings.setSetting("fontSize", "14");
String fontSize = settings.getSetting("fontSize");
```
3. 观察者模式(Observer Pattern)
定义:观察者模式是一种行为型设计模式,它定义了一种一对多的依赖关系,让多个观察者对象同时监听某一个主题对象,当主题对象发生变化时,它的所有观察者都会收到通知并更新自己的状态。
示例代码:假设我们有一个Subject接口和两个实现:WeatherData和StockData,它们都维护着一些数据。我们可以使用观察者模式来让多个观察者监听这些主题对象的变化。
```
public interface Subject {
void registerObserver(Observer o);
void removeObserver(Observer o);
void notifyObservers();
}
public interface Observer {
void update(float temperature, float humidity, float pressure);
}
public class WeatherData implements Subject {
private List<Observer> observers = new ArrayList<>();
private float temperature;
private float humidity;
private float pressure;
@Override
public void registerObserver(Observer o) {
observers.add(o);
}
@Override
public void removeObserver(Observer o) {
observers.remove(o);
}
@Override
public void notifyObservers() {
for (Observer o : observers) {
o.update(temperature, humidity, pressure);
}
}
public void setMeasurements(float temperature, float humidity, float pressure) {
this.temperature = temperature;
this.humidity = humidity;
this.pressure = pressure;
measurementsChanged();
}
private void measurementsChanged() {
notifyObservers();
}
}
public class StockData implements Subject {
private List<Observer> observers = new ArrayList<>();
private String symbol;
private float price;
@Override
public void registerObserver(Observer o) {
observers.add(o);
}
@Override
public void removeObserver(Observer o) {
observers.remove(o);
}
@Override
public void notifyObservers() {
for (Observer o : observers) {
o.update(price);
}
}
public void setPrice(float price) {
this.price = price;
priceChanged();
}
private void priceChanged() {
notifyObservers();
}
}
public class CurrentConditionsDisplay implements Observer {
private float temperature;
private float humidity;
@Override
public void update(float temperature, float humidity, float pressure) {
this.temperature = temperature;
this.humidity = humidity;
display();
}
private void display() {
System.out.println("Current conditions: " + temperature + "F degrees and " + humidity + "% humidity");
}
}
public class StockPriceDisplay implements Observer {
private float price;
@Override
public void update(float price) {
this.price = price;
display();
}
private void display() {
System.out.println("Stock price: $" + price);
}
}
```
我们可以创建一个WeatherData对象和一个StockData对象,并向它们注册两个观察者:CurrentConditionsDisplay和StockPriceDisplay。当WeatherData或StockData对象中的数据发生变化时,它们会通知它们的观察者。
```
WeatherData weatherData = new WeatherData();
StockData stockData = new StockData();
CurrentConditionsDisplay currentConditionsDisplay = new CurrentConditionsDisplay();
StockPriceDisplay stockPriceDisplay = new StockPriceDisplay();
weatherData.registerObserver(currentConditionsDisplay);
stockData.registerObserver(stockPriceDisplay);
weatherData.setMeasurements(80, 65, 30.4f);
stockData.setPrice(100);
```
这就是Java中的三种常用设计模式的简单示例。希望对您有所帮助。
阅读全文