
Java 设计模式最佳实践与应用核心概念设计模式是解决软件设计中常见问题的经典解决方案。掌握设计模式可以提高代码的可复用性、可维护性和可扩展性。本文将介绍常用的设计模式及其在 Java 中的最佳实践。创建型模式1. 单例模式// 饿汉式单例 public class EagerSingleton { private static final EagerSingleton instance new EagerSingleton(); private EagerSingleton() {} public static EagerSingleton getInstance() { return instance; } } // 懒汉式单例双重检查锁定 public class LazySingleton { private volatile static LazySingleton instance; private LazySingleton() {} public static LazySingleton getInstance() { if (instance null) { synchronized (LazySingleton.class) { if (instance null) { instance new LazySingleton(); } } } return instance; } } // 枚举单例推荐 public enum EnumSingleton { INSTANCE; public void doSomething() { // 业务逻辑 } } // 使用示例 public class SingletonUsage { public static void main(String[] args) { EagerSingleton eager EagerSingleton.getInstance(); LazySingleton lazy LazySingleton.getInstance(); EnumSingleton enumSingleton EnumSingleton.INSTANCE; } }2. 工厂模式// 抽象产品 public interface Product { void doSomething(); } // 具体产品 public class ConcreteProductA implements Product { Override public void doSomething() { System.out.println(Product A doing something); } } public class ConcreteProductB implements Product { Override public void doSomething() { System.out.println(Product B doing something); } } // 简单工厂 public class SimpleFactory { public static Product createProduct(String type) { switch (type) { case A: return new ConcreteProductA(); case B: return new ConcreteProductB(); default: throw new IllegalArgumentException(Unknown product type: type); } } } // 抽象工厂 public interface AbstractFactory { Product createProduct(); } public class FactoryA implements AbstractFactory { Override public Product createProduct() { return new ConcreteProductA(); } } public class FactoryB implements AbstractFactory { Override public Product createProduct() { return new ConcreteProductB(); } }3. 建造者模式// 产品类 public class User { private final String firstName; private final String lastName; private final String email; private final int age; private final String phone; private User(Builder builder) { this.firstName builder.firstName; this.lastName builder.lastName; this.email builder.email; this.age builder.age; this.phone builder.phone; } public static class Builder { private final String firstName; private final String lastName; private String email; private int age; private String phone; public Builder(String firstName, String lastName) { this.firstName firstName; this.lastName lastName; } public Builder email(String email) { this.email email; return this; } public Builder age(int age) { this.age age; return this; } public Builder phone(String phone) { this.phone phone; return this; } public User build() { return new User(this); } } } // 使用示例 User user new User.Builder(John, Doe) .email(john.doeexample.com) .age(30) .phone(123-456-7890) .build();结构型模式1. 代理模式// 主题接口 public interface Image { void display(); } // 真实主题 public class RealImage implements Image { private String filename; public RealImage(String filename) { this.filename filename; loadFromDisk(); } private void loadFromDisk() { System.out.println(Loading image: filename); } Override public void display() { System.out.println(Displaying image: filename); } } // 代理主题 public class ProxyImage implements Image { private RealImage realImage; private String filename; public ProxyImage(String filename) { this.filename filename; } Override public void display() { if (realImage null) { realImage new RealImage(filename); } realImage.display(); } } // 使用示例 Image image new ProxyImage(photo.jpg); image.display(); // 第一次加载并显示 image.display(); // 直接显示不再加载2. 装饰器模式// 组件接口 public interface Coffee { double getCost(); String getDescription(); } // 具体组件 public class SimpleCoffee implements Coffee { Override public double getCost() { return 5.0; } Override public String getDescription() { return Simple coffee; } } // 装饰器抽象类 public abstract class CoffeeDecorator implements Coffee { protected Coffee decoratedCoffee; public CoffeeDecorator(Coffee decoratedCoffee) { this.decoratedCoffee decoratedCoffee; } Override public double getCost() { return decoratedCoffee.getCost(); } Override public String getDescription() { return decoratedCoffee.getDescription(); } } // 具体装饰器 public class MilkDecorator extends CoffeeDecorator { public MilkDecorator(Coffee decoratedCoffee) { super(decoratedCoffee); } Override public double getCost() { return super.getCost() 2.0; } Override public String getDescription() { return super.getDescription() , with milk; } } public class SugarDecorator extends CoffeeDecorator { public SugarDecorator(Coffee decoratedCoffee) { super(decoratedCoffee); } Override public double getCost() { return super.getCost() 1.0; } Override public String getDescription() { return super.getDescription() , with sugar; } } // 使用示例 Coffee coffee new SimpleCoffee(); coffee new MilkDecorator(coffee); coffee new SugarDecorator(coffee); System.out.println(Cost: coffee.getCost()); System.out.println(Description: coffee.getDescription());3. 适配器模式// 目标接口 public interface MediaPlayer { void play(String audioType, String fileName); } // 现有接口 public interface AdvancedMediaPlayer { void playVlc(String fileName); void playMp4(String fileName); } // 具体实现 public class VlcPlayer implements AdvancedMediaPlayer { Override public void playVlc(String fileName) { System.out.println(Playing vlc file: fileName); } Override public void playMp4(String fileName) { // 不支持 } } public class Mp4Player implements AdvancedMediaPlayer { Override public void playVlc(String fileName) { // 不支持 } Override public void playMp4(String fileName) { System.out.println(Playing mp4 file: fileName); } } // 适配器 public class MediaAdapter implements MediaPlayer { private AdvancedMediaPlayer advancedMediaPlayer; public MediaAdapter(String audioType) { if (vlc.equalsIgnoreCase(audioType)) { advancedMediaPlayer new VlcPlayer(); } else if (mp4.equalsIgnoreCase(audioType)) { advancedMediaPlayer new Mp4Player(); } } Override public void play(String audioType, String fileName) { if (vlc.equalsIgnoreCase(audioType)) { advancedMediaPlayer.playVlc(fileName); } else if (mp4.equalsIgnoreCase(audioType)) { advancedMediaPlayer.playMp4(fileName); } } } // 客户端 public class AudioPlayer implements MediaPlayer { private MediaAdapter mediaAdapter; Override public void play(String audioType, String fileName) { if (mp3.equalsIgnoreCase(audioType)) { System.out.println(Playing mp3 file: fileName); } else if (vlc.equalsIgnoreCase(audioType) || mp4.equalsIgnoreCase(audioType)) { mediaAdapter new MediaAdapter(audioType); mediaAdapter.play(audioType, fileName); } else { System.out.println(Unsupported format: audioType); } } }行为型模式1. 观察者模式// 主题接口 public interface Subject { void registerObserver(Observer observer); void removeObserver(Observer observer); void notifyObservers(); } // 观察者接口 public interface Observer { void update(String message); } // 具体主题 public class ConcreteSubject implements Subject { private ListObserver observers new ArrayList(); private String message; 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(message); } } public void setMessage(String message) { this.message message; notifyObservers(); } } // 具体观察者 public class ConcreteObserver implements Observer { private String name; public ConcreteObserver(String name) { this.name name; } Override public void update(String message) { System.out.println(name received message: message); } } // 使用示例 Subject subject new ConcreteSubject(); Observer observer1 new ConcreteObserver(Observer 1); Observer observer2 new ConcreteObserver(Observer 2); subject.registerObserver(observer1); subject.registerObserver(observer2); subject.setMessage(Hello World!);2. 策略模式// 策略接口 public interface PaymentStrategy { void pay(double amount); } // 具体策略 public class CreditCardPayment implements PaymentStrategy { private String cardNumber; private String expiryDate; private String cvv; public CreditCardPayment(String cardNumber, String expiryDate, String cvv) { this.cardNumber cardNumber; this.expiryDate expiryDate; this.cvv cvv; } Override public void pay(double amount) { System.out.println(amount paid with credit card: cardNumber); } } public class PayPalPayment implements PaymentStrategy { private String email; private String password; public PayPalPayment(String email, String password) { this.email email; this.password password; } Override public void pay(double amount) { System.out.println(amount paid via PayPal: email); } } // 上下文类 public class ShoppingCart { private ListItem items; public ShoppingCart() { items new ArrayList(); } public void addItem(Item item) { items.add(item); } public void removeItem(Item item) { items.remove(item); } public double calculateTotal() { return items.stream().mapToDouble(Item::getPrice).sum(); } public void pay(PaymentStrategy paymentMethod) { double total calculateTotal(); paymentMethod.pay(total); } } // 使用示例 ShoppingCart cart new ShoppingCart(); cart.addItem(new Item(Item 1, 100)); cart.addItem(new Item(Item 2, 200)); PaymentStrategy creditCard new CreditCardPayment(1234-5678-9012-3456, 12/25, 123); cart.pay(creditCard); PaymentStrategy paypal new PayPalPayment(userexample.com, password); cart.pay(paypal);3. 模板方法模式// 抽象类 public abstract class Game { protected abstract void initialize(); protected abstract void startPlay(); protected abstract void endPlay(); public final void play() { initialize(); startPlay(); endPlay(); } } // 具体实现 public class Cricket extends Game { Override protected void initialize() { System.out.println(Cricket game initialized! Start playing.); } Override protected void startPlay() { System.out.println(Cricket game started. Enjoy the game!); } Override protected void endPlay() { System.out.println(Cricket game finished!); } } public class Football extends Game { Override protected void initialize() { System.out.println(Football game initialized! Start playing.); } Override protected void startPlay() { System.out.println(Football game started. Enjoy the game!); } Override protected void endPlay() { System.out.println(Football game finished!); } } // 使用示例 Game cricket new Cricket(); cricket.play(); Game football new Football(); football.play();最佳实践选择合适的模式根据问题选择最合适的设计模式不要过度设计简单问题不需要复杂模式遵循开闭原则对扩展开放对修改关闭保持单一职责每个类只负责一个功能依赖倒置依赖抽象而不是具体实现组合优于继承优先使用组合而非继承最小知识原则减少对象之间的依赖文档说明为使用设计模式的代码添加注释实际应用场景框架设计Spring、Hibernate 等框架广泛使用设计模式业务逻辑处理复杂的业务流程代码重构改进现有代码的结构团队协作提高代码的可读性和可维护性总结设计模式是软件开发的宝贵财富。通过学习和应用设计模式可以提高代码质量加速开发过程促进团队协作。在实际项目中需要根据具体情况灵活运用各种设计模式。别叫我大神叫我 Alex 就好。这其实可以更优雅一点合理的设计模式让代码变得更加优雅和可维护。