Java设计模式汇总篇(全面详细)
发布人:shili8
发布时间:2024-12-27 10:48
阅读次数:0
**Java 设计模式汇总篇**
设计模式是软件开发中的一套经验法则,它们通过定义问题的解决方案来避免在程序设计过程中出现的常见错误。设计模式可以帮助我们写出更高质量、更易维护和更易扩展的代码。
本文将全面详细地介绍 Java 设计模式,包括23 种经典设计模式,以及它们的应用场景、优点和缺点。
### 一、单例模式 (Singleton Pattern)
**定义:** 单例模式是一种创建型模式,它保证一个类只有一个实例,并提供全局访问该实例。
**应用场景:**
* 需要在整个系统中共享某个资源时。
* 需要在多线程环境下共享某个资源时。
**优点:**
*由于只创建一次实例,因此节省了内存空间。
* 全局访问该实例非常方便。
**缺点:**
* 如果没有正确实现单例模式,可能会导致多个实例被创建。
* 单例模式不支持继承。
javapublic class Singleton {
// 私有构造函数 private Singleton() {}
// 静态私有变量 private static Singleton instance = null;
// 公共方法,返回单例实例 public static Singleton getInstance() {
if (instance == null) {
synchronized (Singleton.class) {
if (instance == null) {
instance = new Singleton();
}
}
}
return instance;
}
public void doSomething() {
System.out.println("Doing something...");
}
}
### 二、工厂模式 (Factory Pattern)
**定义:** 工厂模式是一种创建型模式,它提供了一个用于创建对象的接口,而不需要暴露对象的具体实现。
**应用场景:**
* 需要根据不同的条件创建不同类型的对象时。
* 需要在系统中注册和管理多个类时。
**优点:**
* 提高了代码的重用性和灵活性。
* 可以更好地控制对象的创建过程。
**缺点:**
* 增加了系统的复杂度。
* 需要额外的成本来维护工厂类。
javapublic abstract class Animal {
public abstract void sound();
}
public class Dog extends Animal {
@Override public void sound() {
System.out.println("Woof!");
}
}
public class Cat extends Animal {
@Override public void sound() {
System.out.println("Meow!");
}
}
public class AnimalFactory {
public static Animal createAnimal(String type) {
if (type.equals("dog")) {
return new Dog();
} else if (type.equals("cat")) {
return new Cat();
} else {
throw new RuntimeException("Invalid animal type");
}
}
public static void main(String[] args) {
Animal dog = createAnimal("dog");
Animal cat = createAnimal("cat");
dog.sound(); // Woof!
cat.sound(); // Meow!
}
}
### 三、观察者模式 (Observer Pattern)
**定义:** 观察者模式是一种行为型模式,它定义了对象间的一对多关系,使得一个对象的状态改变时,其他对象都能得到通知。
**应用场景:**
* 需要在系统中实现事件驱动机制时。
* 需要在系统中注册和管理多个观察者时。
**优点:**
* 提高了系统的灵活性和扩展性。
* 可以更好地控制对象之间的关系。
**缺点:**
* 增加了系统的复杂度。
* 需要额外的成本来维护观察者类。
javapublic interface Observer {
void update(String message);
}
public class WeatherStation implements Observer {
private String weather;
public void setWeather(String weather) {
this.weather = weather;
notifyObservers();
}
@Override public void update(String message) {
System.out.println("Received weather update: " + message);
}
}
public class ForecastDisplay implements Observer {
@Override public void update(String message) {
System.out.println("Forecast updated: " + message);
}
}
public class WeatherStationMain {
public static void main(String[] args) {
WeatherStation station = new WeatherStation();
ForecastDisplay display = new ForecastDisplay();
station.addObserver(display);
station.setWeather("Sunny");
station.setWeather("Rainy");
}
}
### 四、策略模式 (Strategy Pattern)
**定义:** 策略模式是一种行为型模式,它定义了算法家族,分别封装在不同的类中,使得它们可以相互替换。
**应用场景:**
* 需要根据不同条件选择不同的算法时。
* 需要在系统中注册和管理多个策略时。
**优点:**
* 提高了代码的重用性和灵活性。
* 可以更好地控制对象之间的关系。
**缺点:**
* 增加了系统的复杂度。
* 需要额外的成本来维护策略类。
javapublic interface PaymentStrategy {
void pay(int amount);
}
public class CreditCardPayment implements PaymentStrategy {
@Override public void pay(int amount) {
System.out.println("Paid " + amount + " using credit card");
}
}
public class PayPalPayment implements PaymentStrategy {
@Override public void pay(int amount) {
System.out.println("Paid " + amount + " using PayPal");
}
}
public class ShoppingCart {
private PaymentStrategy paymentStrategy;
public void setPaymentStrategy(PaymentStrategy paymentStrategy) {
this.paymentStrategy = paymentStrategy;
}
public void checkout() {
int totalAmount =100;
paymentStrategy.pay(totalAmount);
}
}
### 五、模板方法模式 (Template Method Pattern)
**定义:** 模板方法模式是一种行为型模式,它在一个方法中定义了一个算法的骨架,而将一些步骤延迟到子类中。
**应用场景:**
* 需要根据不同条件选择不同的算法时。
* 需要在系统中注册和管理多个模板方法时。
**优点:**
* 提高了代码的重用性和灵活性。
* 可以更好地控制对象之间的关系。
**缺点:**
* 增加了系统的复杂度。
* 需要额外的成本来维护模板方法类。
javapublic abstract class Game {
public final void play() {
initialize();
startGame();
endGame();
}
protected abstract void initialize();
protected abstract void startGame();
protected abstract void endGame();
}
public class ChessGame extends Game {
@Override protected void initialize() {
System.out.println("Initializing chess game...");
}
@Override protected void startGame() {
System.out.println("Starting chess game...");
}
@Override protected void endGame() {
System.out.println("Ending chess game...");
}
}
### 六、适配器模式 (Adapter Pattern)
**定义:** 适配器模式是一种结构型模式,它使得两个不兼容的接口能够一起工作。
**应用场景:**
* 需要将一个类的接口转换成另一个类所期望的接口时。
* 需要在系统中注册和管理多个适配器时。
**优点:**
* 提高了代码的重用性和灵活性。
* 可以更好地控制对象之间的关系。
**缺点:**
* 增加了系统的复杂度。
* 需要额外的成本来维护适配器类。
javapublic interface Duck {
void quack();
}
public class Turkey implements Quackable {
@Override public void quack() {
System.out.println("Gobble!");
}
}
public class TurkeyAdapter implements Duck {
private Turkey turkey;
public TurkeyAdapter(Turkey turkey) {
this.turkey = turkey;
}
@Override public void quack() {
turkey.quack();
}
}
### 七、桥接模式 (Bridge Pattern)
**定义:** 桥接模式是一种结构型模式,它分离了抽象和实现,使得两者可以独立变化。
**应用场景:**
* 需要在系统中注册和管理多个类时。
* 需要将一个类的接口转换成另一个类所期望的接口时。
**优点:**
* 提高了代码的重用性和灵活性。
* 可以更好地控制对象之间的关系。
**缺点:**
* 增加了系统的复杂度。
* 需要额外的成本来维护桥接类。
javapublic

