当前位置: 首页 > news >正文

Java 设计模式:最佳实践与应用

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.doe@example.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 List<Observer> 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 List<Item> 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("user@example.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();

最佳实践

  1. 选择合适的模式:根据问题选择最合适的设计模式
  2. 不要过度设计:简单问题不需要复杂模式
  3. 遵循开闭原则:对扩展开放,对修改关闭
  4. 保持单一职责:每个类只负责一个功能
  5. 依赖倒置:依赖抽象而不是具体实现
  6. 组合优于继承:优先使用组合而非继承
  7. 最小知识原则:减少对象之间的依赖
  8. 文档说明:为使用设计模式的代码添加注释

实际应用场景

  • 框架设计:Spring、Hibernate 等框架广泛使用设计模式
  • 业务逻辑:处理复杂的业务流程
  • 代码重构:改进现有代码的结构
  • 团队协作:提高代码的可读性和可维护性

总结

设计模式是软件开发的宝贵财富。通过学习和应用设计模式,可以提高代码质量,加速开发过程,促进团队协作。在实际项目中,需要根据具体情况灵活运用各种设计模式。

别叫我大神,叫我 Alex 就好。这其实可以更优雅一点,合理的设计模式让代码变得更加优雅和可维护。

http://www.jsqmd.com/news/783940/

相关文章:

  • 经验分享:工业采购必须了解的旋进旋涡流量计选型知识 - 速递信息
  • 为AI智能体构建持久化记忆:Stratum架构设计与工程实践
  • 基于LoRA与指令微调的中文Vicuna大模型本地部署与优化指南
  • WALAR:基于强化学习的低资源机器翻译优化方案
  • 给RK3568的Linux 4.19内核打RT-Preempt补丁,我踩过的那些坑都帮你填好了
  • FISSION-GRPO:基于强化学习的智能错误恢复系统
  • 台州普金办公设备:椒江打印机租赁公司电话 - LYL仔仔
  • CANN Ascend C算子开发套件
  • 2026丽江旅拍婚纱照梯队横评:T0/T1/T2全景拆解,第一名为何无法撼动? - 江湖评测
  • CANN/shmem SIMT远程内存访问示例
  • ru-text:为AI编码助手注入俄语文本质量灵魂的规则引擎
  • Open-Harness:一站式开源AI模型高效推理与微调框架解析
  • CANN/driver DCMI获取设备频率API
  • 98.吃透YOLOv8架构(C2f+解耦头),手把手落地行人检测项目
  • 7个Vlog背景音乐素材宝藏网站,找歌不费劲儿还不侵权 - 拾光而行
  • CANN TensorFlow迭代循环加载
  • 网络安全之 Burp Suite 深度解析与实战
  • 从RTL到可执行:手把手拆解基于FPGA的硬件仿真器前端三步骤(Analyze, Elaboration, Synthesis)
  • 2026年亲测靠谱:3个私藏AIGC降重工具+免费降AI指令,解决论文AI率过高问题 - 降AI实验室
  • 孤舟笔记 JVM篇三 JVM如何判断一个对象可以被回收?可达性分析比引用计数强在哪
  • CANN/pyasc数据连接API文档
  • 低空经济工业互联网中的数字孪生与智能体:IOC与平台协同的演进逻辑
  • ARM系统控制与调试接口:PPU与DAP详解
  • 有限单边响应游戏中的蒙特卡洛反事实遗憾最小化
  • 别再死记硬背API了!图解 LVGL 的“类”(lv_obj_class_t)与“对象”(lv_obj_t)继承体系
  • 别急着重启!Redis突然连不上的5分钟排查手册(附CentOS 7实战命令)
  • 宁波双利再生资源:镇海废旧金属回收推荐几家公司 - LYL仔仔
  • 抖音下载器终极指南:从零开始掌握批量下载与无水印提取
  • ChatGPT如何通过大学计算机安全课程考核?实验揭示AI对教育评估的冲击与机遇
  • 南京情绪障碍心理医院选择:专业机构服务解析 - 品牌排行榜