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

八大设计模式

设计模式在日常软件开发中的重要性

请添加图片描述

目录

  1. 单例模式
  2. 工厂模式
  3. 策略模式
  4. 代理模式
  5. 观察者模式
  6. 装饰器模式
  7. 模板方法模式
  8. 建造者模式
  9. 总结

单例模式

单例模式确保一个类只有一个实例,通常用于管理共享资源,如配置、缓存、线程池等。

代码实现:双重检查锁

public class Singleton {private static volatile Singleton instance;private Singleton() {}public static Singleton getInstance() {if (instance == null) {synchronized (Singleton.class) {if (instance == null) {instance = new Singleton();}}}return instance;}
}

工厂模式

工厂模式用于封装对象的创建逻辑,特别是当类实例化过程复杂时,可以降低耦合度。

代码实现:简单工厂

public class PaymentFactory {public static Payment createPayment(String type) {switch (type) {case "AliPay":return new AliPay();case "WeChatPay":return new WeChatPay();default:throw new IllegalArgumentException("Unknown payment type");}}
}

策略模式

策略模式将不同算法封装为独立类,并允许在运行时选择不同的策略。

代码实现:促销策略

public interface PromotionStrategy {void applyPromotion();
}public class DiscountStrategy implements PromotionStrategy {@Overridepublic void applyPromotion() {System.out.println("Applying discount...");}
}public class PromotionContext {private PromotionStrategy strategy;public PromotionContext(PromotionStrategy strategy) {this.strategy = strategy;}public void executePromotion() {strategy.applyPromotion();}
}

代理模式

代理模式通过代理对象控制对目标对象的访问,常用于权限控制、日志记录等场景。

代码实现:静态代理

public interface Service {void execute();
}public class RealService implements Service {@Overridepublic void execute() {System.out.println("Executing real service...");}
}public class ServiceProxy implements Service {private RealService realService;@Overridepublic void execute() {System.out.println("Checking permissions...");if (realService == null) {realService = new RealService();}realService.execute();}
}

观察者模式

观察者模式定义一对多的依赖,当一个对象状态变化时,所有依赖它的对象都会收到通知。

代码实现:事件通知

public interface Observer {void update(String message);
}public class User implements Observer {private String name;public User(String name) {this.name = name;}@Overridepublic void update(String message) {System.out.println(name + " received message: " + message);}
}public class Weibo {private List<Observer> observers = new ArrayList<>();public void follow(Observer observer) {observers.add(observer);}public void post(String message) {for (Observer observer : observers) {observer.update(message);}}
}

装饰器模式

装饰器模式在不改变原始类的基础上,动态扩展其功能。

代码实现:咖啡加料

public interface Coffee {String getDescription();double getCost();
}public class SimpleCoffee implements Coffee {@Overridepublic String getDescription() {return "Simple Coffee";}@Overridepublic double getCost() {return 5.0;}
}public class MilkDecorator implements Coffee {private Coffee coffee;public MilkDecorator(Coffee coffee) {this.coffee = coffee;}@Overridepublic String getDescription() {return coffee.getDescription() + ", Milk";}@Overridepublic double getCost() {return coffee.getCost() + 1.5;}
}

模板方法模式

模板方法模式定义一个算法的骨架,把具体的实现留给子类。

代码实现:任务执行模板

public abstract class Task {public final void execute() {init();doWork();cleanup();}protected abstract void init();protected abstract void doWork();protected void cleanup() {System.out.println("Default cleanup...");}
}public class DataProcessingTask extends Task {@Overrideprotected void init() {System.out.println("Initializing data...");}@Overrideprotected void doWork() {System.out.println("Processing data...");}
}

建造者模式

建造者模式用于创建复杂对象,特别是当对象有多个可选参数时。

代码实现:构建HTTP请求

public class HttpRequest {private String method;private String url;private String body;private HttpRequest(Builder builder) {this.method = builder.method;this.url = builder.url;this.body = builder.body;}public static class Builder {private String method;private String url;private String body;public Builder method(String method) {this.method = method;return this;}public Builder url(String url) {this.url = url;return this;}public Builder body(String body) {this.body = body;return this;}public HttpRequest build() {return new HttpRequest(this);}}
}

总结

在软件开发的广阔天地中,设计模式不仅是解决特定问题的模板,更是提升代码质量、可维护性和可扩展性的有力工具。通过本文的探讨,我们深入了解了8种设计模式:单例模式、工厂模式、策略模式、代理模式、观察者模式、装饰器模式、模板方法模式和建造者模式。每种模式都以其独特的方式,帮助我们应对软件开发中的复杂性,提供了一种清晰、结构化的方法来构建灵活且健壮的系统。

设计模式的价值

  1. 代码重用与解耦:设计模式通过提供通用解决方案,减少了重复代码,降低了模块间的耦合度,使得代码更易于管理和维护。
  2. 提高可读性和可维护性:遵循设计模式编写的代码结构清晰,易于新开发人员理解,从而降低了代码维护的难度。
  3. 增强代码的灵活性和可扩展性:设计模式使得添加新功能或修改现有功能变得更加简单,无需大规模重构现有代码。
  4. 促进最佳实践:设计模式是多年软件开发经验的结晶,遵循这些模式可以避免一些常见的陷阱,促进最佳实践。

设计模式的实际应用

在JDK和Spring框架中,设计模式的应用无处不在,这不仅证明了它们的有效性,也为我们在实际项目中应用这些模式提供了参考。例如,Spring框架中的单例模式管理着Bean的生命周期,工厂模式在创建Bean时发挥着重要作用,而策略模式则在动态选择数据库查询策略时大显身手。

学习设计模式的建议

  1. 理论与实践相结合:不仅要理解每种设计模式的理论基础,更要通过实际编码来加深理解。
  2. 适度应用:设计模式是解决问题的工具,但不应过度使用或滥用。在适当的场景选择合适的模式,才能发挥其最大价值。
  3. 持续学习:随着技术的发展,新的模式和实践不断出现,持续学习是保持技术竞争力的关键。

结语

设计模式的学习是一个持续的过程,它要求我们不断地实践、反思和改进。希望本文能够作为您学习设计模式旅程中的一个起点,激发您在实际项目中探索和应用这些强大工具的热情。如果您有任何疑问、见解或经验分享,欢迎在评论区交流,让我们共同进步。。

http://www.lryc.cn/news/505424.html

相关文章:

  • 神经网络基础-初识神经网络
  • 《计算机视觉:瓶颈之辩与未来之路》
  • Centos gcc 12.3 安装
  • B站bilibili视频转文字字幕下载方法
  • vue CSS 自定义宽高 翻页 剥离 效果
  • uniapp使用百度地图配置了key,但是显示Map key not configured
  • Leetcode42-环形链表
  • C语言进阶(2) ---- 指针的进阶
  • 使用Python筛选图片
  • GESP CCF python五级编程等级考试认证真题 2024年12月
  • URL的概念与格式
  • 【Elasticsearch】高亮搜索:从原理到Web呈现
  • samout llm解码 幻觉更低更稳定
  • 单片机:实现多任务处理(附带源码)
  • 负载均衡oj项目:介绍
  • 剑指Offer 03比特位计数
  • 多音轨视频使用FFmpeg删除不要音轨方法
  • elasticsearch 使用enrich processor填充数据
  • VMProtect:软件保护与安全的全面解决方案
  • Web 毕设篇-适合小白、初级入门练手的 Spring Boot Web 毕业设计项目:教室信息管理系统(前后端源码 + 数据库 sql 脚本)
  • 第十二篇:linux下socket本地套接字通讯
  • Spring Boot 2.1.7 数据源自动加载过程详解
  • 【Vue.js 3.0】provide 、inject 函数详解
  • JVM(Java虚拟机)的虚拟机栈
  • Elasticsearch02-安装7.x
  • iPhone恢复技巧:如何从 iPhone 恢复丢失的照片
  • vba批量化调整word的图和图表标题
  • 【Flutter_Web】Flutter编译Web第二篇(webview篇):flutter_inappwebview如何改造方法,变成web之后数据如何交互
  • 【C语言的奥秘11】指针知识点总结(续)
  • excel 列名是数据表 的字段名 ,单元格的值 是数据表对应字段的值,生成sql插入语句