工作七年总结:这 7 种设计模式,解决 99% 的 Java 开发场景
(??金石瓜分计划??天倒计时,速戳上图了解详情??)
Java 开发中最常用的七大设计模式:场景解析与代码实现?设计模式是软件开发中经过验证的最佳实践,合理运用设计模式可以提升代码的可维护性、可扩展性和可读性。本文将结合实际场景,详细介绍 Java 开发中最常用的「七大设计模式」,并附带有注释的代码示例。
?一、单例模式(Singleton Pattern)「模式定义」:确保一个类只有一个实例,并提供全局访问点。
「适用场景」:
全局唯一的资源管理(如线程池、缓存、日志对象)。需要节省内存资源的场景(仅创建一个实例)。实现方式:枚举单例(线程安全、抗反射攻击)/*** 枚举单例(推荐)* 优点:线程安全,防止反射攻击,代码简洁*/publicenumSingleton{ INSTANCE;// 唯一实例
// 示例方法:模拟获取配置 publicStringgetConfig() { return"config from singleton"; }}
// 使用示例publicclassClient{ publicstaticvoidmain(String[] args) { Singletoninstance1 =Singleton.INSTANCE; Singletoninstance2 =Singleton.INSTANCE; System.out.println(instance1 == instance2);// 输出 true }}二、工厂模式(Factory Pattern)「模式定义」:通过工厂类封装对象的创建逻辑,客户端无需知道具体实现类。
「适用场景」:
对象创建逻辑复杂(如参数校验、初始化步骤)。需要解耦对象创建和使用的场景。实现方式:简单工厂(创建不同日志处理器)// 日志接口interfaceLogger{ voidlog(Stringmessage);}
// 控制台日志实现classConsoleLoggerimplementsLogger{ @Override publicvoidlog(Stringmessage) { System.out.println("Console: "+ message); }}
// 文件日志实现classFileLoggerimplementsLogger{ @Override publicvoidlog(Stringmessage) { System.out.println("File: "+ message); }}
// 工厂类classLoggerFactory{ // 根据类型创建日志对象 publicstaticLoggercreateLogger(Stringtype) { if("console".equalsIgnoreCase(type)) { returnnewConsoleLogger(); }elseif("file".equalsIgnoreCase(type)) { returnnewFileLogger(); }else{ thrownewIllegalArgumentException("Unsupported logger type: "+type); } }}
// 使用示例publicclassClient{ publicstaticvoidmain(String[] args) { LoggerconsoleLogger =LoggerFactory.createLogger("console"); consoleLogger.log("Hello, World!");// 输出:Console: Hello, World! }}三、策略模式(Strategy Pattern)「模式定义」:定义一系列算法,将每个算法封装起来,使其可以相互替换。
「适用场景」:
算法动态切换(如支付方式、排序策略)。避免多重条件判断(将条件逻辑封装为策略类)。实现方式:支付策略(支付宝 / 微信支付)// 支付策略接口interfacePaymentStrategy{ voidpay(doubleamount);}
// 支付宝支付策略classAlipayStrategyimplementsPaymentStrategy{ @Override publicvoidpay(doubleamount){ System.out.println("使用支付宝支付:"+ amount +"元"); }}
// 微信支付策略classWechatPayStrategyimplementsPaymentStrategy{ @Override publicvoidpay(doubleamount){ System.out.println("使用微信支付:"+ amount +"元"); }}
// 上下文类(管理策略)classPaymentContext{ privatePaymentStrategy strategy;
publicPaymentContext(PaymentStrategy strategy){ this.strategy = strategy; }
publicvoidsetStrategy(PaymentStrategy strategy){ this.strategy = strategy; }
publicvoidexecutePayment(doubleamount){ strategy.pay(amount); }}
// 使用示例publicclassClient{ publicstaticvoidmain(String[] args){ PaymentContextcontext=newPaymentContext(newAlipayStrategy()); context.executePayment(199.9);// 输出:使用支付宝支付:199.9元
context.setStrategy(newWechatPayStrategy()); context.executePayment(88.8);// 输出:使用微信支付:88.8元 }}四、观察者模式(Observer Pattern)「模式定义」:定义对象间的一种一对多依赖关系,当一个对象状态改变时,其依赖的对象都能得到通知并自动更新。
「适用场景」:
消息订阅与发布(如事件总线、通知系统)。监听状态变化(如股票价格变动、天气预警)。实现方式:天气观察者(观察者订阅天气更新)// 主题接口(被观察者)interfaceWeatherSubject{ voidaddObserver(WeatherObserver observer);// 添加观察者 voidremoveObserver(WeatherObserver observer);// 移除观察者 voidnotifyObservers();// 通知所有观察者 voidsetTemperature(doubletemperature);// 更新温度}
// 观察者接口interfaceWeatherObserver{ voidupdate(doubletemperature);// 接收更新通知}
// 具体主题(天气数据中心)classWeatherDataCenterimplementsWeatherSubject{ privatedoubletemperature; privatefinalListWeatherObserver observers =newArrayList();
@Override publicvoidaddObserver(WeatherObserver observer){ observers.add(observer); }
@Override publicvoidremoveObserver(WeatherObserver observer){ observers.remove(observer); }
@Override publicvoidnotifyObservers(){ for(WeatherObserver observer : observers) { observer.update(temperature);// 推送更新 } }
@Override publicvoidsetTemperature(doubletemperature){ this.temperature = temperature; notifyObservers();// 温度变化时主动通知 }}
// 具体观察者(手机APP)classMobileAppObserverimplementsWeatherObserver{ privatefinalString name;
publicMobileAppObserver(String name){ this.name = name; }
@Override publicvoidupdate(doubletemperature){ System.out.println(name +" 收到通知:当前温度为 "+ temperature +"℃"); }}
// 使用示例publicclassClient{ publicstaticvoidmain(String[] args){ WeatherDataCentersubject=newWeatherDataCenter(); WeatherObserverapp1=newMobileAppObserver("天气通"); WeatherObserverapp2=newMobileAppObserver("彩云天气");
subject.addObserver(app1); subject.addObserver(app2);
subject.setTemperature(25.5);// 温度变化,触发通知 // 输出: // 天气通 收到通知:当前温度为 25.5℃ // 彩云天气 收到通知:当前温度为 25.5℃ }}五、装饰器模式(Decorator Pattern)「模式定义」:动态地给一个对象添加额外的职责,比继承更灵活。
「适用场景」:
扩展对象功能(如 IO 流的缓冲、加密装饰)。避免通过继承导致类爆炸(多层继承)。实现方式:咖啡调味(基础咖啡 + 牛奶 / 糖浆装饰)// 饮料接口interfaceBeverage{ StringgetDescription();// 获取描述 doublecost();// 计算价格}
// 基础咖啡(具体组件)classBasicCoffeeimplementsBeverage{ @Override publicStringgetDescription(){ return"基础咖啡"; }
@Override publicdoublecost(){ return15.0;// 基础价格 }}
// 装饰器抽象类(继承饮料接口,持有被装饰对象)abstractclassBeverageDecoratorimplementsBeverage{ protectedfinalBeverage beverage;// 被装饰的饮料
publicBeverageDecorator(Beverage beverage){ this.beverage = beverage; }
@Override publicabstractStringgetDescription();
@Override publicabstractdoublecost();}
// 牛奶装饰器(具体装饰器)classMilkDecoratorextendsBeverageDecorator{ publicMilkDecorator(Beverage beverage){ super(beverage); }
@Override publicStringgetDescription(){ returnbeverage.getDescription() +" + 牛奶";// 扩展描述 }
@Override publicdoublecost(){ returnbeverage.cost() +3.0;// 增加牛奶的价格 }}
// 糖浆装饰器(具体装饰器)classSyrupDecoratorextendsBeverageDecorator{ publicSyrupDecorator(Beverage beverage){ super(beverage); }
@Override publicStringgetDescription(){ returnbeverage.getDescription() +" + 糖浆"; }
@Override publicdoublecost(){ returnbeverage.cost() +2.0; }}
// 使用示例publicclassClient{ publicstaticvoidmain(String[] args){ // 基础咖啡 + 牛奶 + 糖浆 Beveragecoffee=newBasicCoffee(); coffee =newMilkDecorator(coffee); coffee =newSyrupDecorator(coffee);
System.out.println("饮料:"+ coffee.getDescription()); System.out.println("价格:"+ coffee.cost() +"元"); // 输出: // 饮料:基础咖啡 + 牛奶 + 糖浆 // 价格:20.0元 }}六、适配器模式(Adapter Pattern)「模式定义」:将一个类的接口转换成客户希望的另一个接口,使不兼容的接口可以协同工作。
「适用场景」:
兼容旧系统接口(如将第三方库接口转换为内部接口)。类的接口与客户需求不匹配,但又不能修改原有类。实现方式:电压适配器(220V 转 5V)// 目标接口(手机需要5V充电)interfaceFiveVolt{ intgetVolt5();// 获取5V电压}
// 被适配者(电源提供220V电压)classAC220Volt{ publicintgetVolt220(){ return220;// 原始电压 }}
// 适配器类(将220V转换为5V)classVoltageAdapterextendsAC220VoltimplementsFiveVolt{ @Override publicintgetVolt5(){ intvolt220 = getVolt220(); // 模拟降压逻辑(实际需物理电路) returnvolt220 /44;// 220V - 5V }}
// 使用示例publicclassClient{ publicstaticvoidmain(String[] args){ FiveVolt charger =newVoltageAdapter(); System.out.println("手机充电电压:"+ charger.getVolt5() +"V");// 输出:5V }}七、模板方法模式(Template Method Pattern)「模式定义」:定义一个算法的骨架,将具体步骤延迟到子类实现,子类可以在不改变算法结构的情况下重新定义某些步骤。
「适用场景」:
多个子类有公共逻辑(如文件操作流程、审批流程)。避免代码重复,统一算法骨架。实现方式:文件处理器(读取文件 + 解析逻辑)// 模板类(定义文件处理流程)abstractclassFileProcessor{ // 模板方法:固定处理流程 publicfinalvoidprocessFile(Stringpath) { Stringcontent =readFile(path);// 读取文件(子类实现) parseContent(content);// 解析内容(子类实现) saveToDatabase(content);// 保存到数据库(公共逻辑) }
// 子类必须实现的抽象方法 protectedabstractStringreadFile(Stringpath);
protectedabstractvoidparseContent(Stringcontent);
// 公共方法(子类可覆盖,默认实现) protectedvoidsaveToDatabase(Stringcontent) { System.out.println("保存内容到数据库:"+ content); }}
// CSV文件处理器(具体子类)classCSVProcessorextendsFileProcessor{ @Override protectedStringreadFile(Stringpath) { return"模拟读取CSV文件内容:姓名,年龄\n张三,25"; }
@Override protectedvoidparseContent(Stringcontent) { System.out.println("解析CSV内容:"+ content); }
// 覆盖公共方法(可选) @Override protectedvoidsaveToDatabase(Stringcontent) { System.out.println("特殊处理:将CSV内容存入专用表"); }}
// 使用示例publicclassClient{ publicstaticvoidmain(String[] args) { FileProcessorprocessor =newCSVProcessor(); processor.processFile("data.csv"); // 输出: // 解析CSV内容:姓名,年龄\n张三,25 // 特殊处理:将CSV内容存入专用表 }}总结:设计模式的核心思想「单一职责原则」:每个类只负责单一功能(如工厂类只负责创建对象)。「开闭原则」:对扩展开放,对修改关闭(如策略模式新增策略无需修改原有代码)。「组合复用原则」:优先使用组合 / 聚合,而非继承(如装饰器模式通过持有对象实现功能扩展)。AI编程资讯AI Coding专区指南:https://aicoding.juejin.cn/aicoding
点击"阅读原文"了解详情~
阅读原文
网站开发网络凭借多年的网站建设经验,坚持以“帮助中小企业实现网络营销化”为宗旨,累计为4000多家客户提供品质建站服务,得到了客户的一致好评。如果您有网站建设、网站改版、域名注册、主机空间、手机网站建设、网站备案等方面的需求...
请立即点击咨询我们或拨打咨询热线:13245491521 13245491521 ,我们会详细为你一一解答你心中的疑难。 项目经理在线