一、Java设计模式的核心价值
Java设计模式是软件开发的最好方法,它解决了很多问题,让代码更好维护、扩展和读。初学者或老手,懂设计模式能优化代码,为建复杂系统提供标准答案。
关键词:Java设计模式、单例模式、工厂模式、策略模式、Spring框架
二、设计模式的三大分类
Java设计模式根据目的和应用场景可分为以下三类:
创建型模式(Creational Patterns)
作用:封装对象创建,让使用者不用了解构造细节。
典型模式:单例模式、工厂模式、建造者模式、原型模式。
结构型模式(Structural Patterns)
功能:改进类与对象的搭配,让系统更灵活。
典型模式:适配器模式、装饰器模式、代理模式。
行为型模式(Behavioral Patterns)
作用:制定对象间的交流规矩,让算法和职责不再搅在一起。
典型模式:观察者模式、策略模式、责任链模式。
三、Java开发中最常用的七大设计模式
1. 单例模式(Singleton Pattern)
定义:保证类只存在一个实例,并全局可访问。
适用地方:全局中唯一管理资源,例如线程池或日志工具。
实现方式:枚举单例(线程安全、抗反射攻击)。
代码示例:
Java
深色版本
public enum Singleton {
INSTANCE; // 唯一实例
public void showMessage() {
System.out.println("Hello from Singleton!");
}
}
2. 工厂模式(Factory Pattern)
定义:通过工厂类封装对象的创建逻辑,客户端无需知道具体实现类。
适用地方:对象创建很难或要选实现类时。
代码示例:
Java
深色版本
interface Logger {
void log(String message);
}
class ConsoleLogger implements Logger {
public void log(String message) {
System.out.println("Console: " + message);
}
}
class LoggerFactory {
public static Logger createLogger(String type) {
if ("console".equals(type)) return new ConsoleLogger();
else throw new IllegalArgumentException("Unsupported logger type");
}
}
3. 策略模式(Strategy Pattern)
定义:算法封成独立类,运行时能变策略。
适用地方:电商打折,付款方法选择等逻辑。
代码示例:
Java
深色版本
interface PromotionStrategy {
void applyPromotion();
}
class DiscountStrategy implements PromotionStrategy {
public void applyPromotion() {
System.out.println("Applying discount...");
}
}
class PromotionContext {
private PromotionStrategy strategy;
public PromotionContext(PromotionStrategy strategy) {
this.strategy = strategy;
}
public void executePromotion() {
strategy.applyPromotion();
}
}
4. 观察者模式(Observer Pattern)
定义:对象间一对多关系,一个对象变了,依赖者都会更新。
应用场景:事件系统(消息推送、实时数据看)。
代码示例:
Java
深色版本
interface Observer {
void update(String message);
}
class ConcreteObserver implements Observer {
public void update(String message) {
System.out.println("Received: " + message);
}
}
class Subject {
List<Observer> observers = new ArrayList<>();
public void addObserver(Observer observer) {
observers.add(observer);
}
public void notifyObservers(String message) {
for (Observer observer : observers) {
observer.update(message);
}
}
}
5. 代理模式(Proxy Pattern)
定义:为其他对象提供代理,控制对目标对象的访问。
适用地方:懒加载、远程调用控制权限。
代码示例:
Java
深色版本
interface Image {
void display();
}
class RealImage implements Image {
public void display() {
System.out.println("Displaying real image...");
}
}
class ProxyImage implements Image {
private RealImage realImage;
public void display() {
if (realImage == null) realImage = new RealImage();
realImage.display();
}
}
6. 装饰器模式(Decorator Pattern)
定义:动态地为对象添加职责,避免继承导致的子类爆炸。
适用地方:功能增加(例如IO流操作)。
代码示例:
Java
深色版本
abstract class Coffee {
public abstract double cost();
}
class SimpleCoffee extends Coffee {
public double cost() { return 2.0; }
}
class MilkDecorator extends Coffee {
private Coffee coffee;
public MilkDecorator(Coffee coffee) { this.coffee = coffee; }
public double cost() { return coffee.cost() + 0.5; }
}
7. 模板方法模式(Template Method Pattern)
定义:就是建个算法的框架,步骤留给子类去完成。
适用地方:流程一样但步骤会变,像测试框架。
代码示例:
Java
深色版本
abstract class TestFramework {
public void runTest() {
initialize();
executeTest();
finalize();
}
abstract void executeTest();
void initialize() { System.out.println("Initializing..."); }
void finalize() { System.out.println("Finalizing..."); }
}
class ConcreteTest extends TestFramework {
void executeTest() { System.out.println("Executing test..."); }
}
四、Java设计模式的优缺点分析
优点 缺点
1. 提升代码复用,少写重复代码,开发更快。 增加学习费,要知道模式和在哪能用。
2. 增强系统扩展性:通过解耦设计,方便新增功能。 2. 可能导致过度设计:简单问题滥用模式反而复杂化。
3. 提升代码可维护,结构要清楚,好让以后升级。 3. 性能开销:代理模式等模式可能产生多余的花费。
五,Java设计模式的实际使用
Spring框架的设计模式
单例模式:Spring容器默认以单例管理Bean。
工厂模式:BeanFactory动态创建和管理对象。
代理模式:AOP通过动态代理实现切面功能。
电商系统中的策略模式
支持满减、打折等促销,动态换不需要改核心逻辑。
日志系统中的观察者模式
多个日志处理器(文件、数据库、控制台)订阅日志事件,实现解耦。
六、Java设计模式的最佳实践
合理选择模式:根据业务需求选择合适的模式,避免“为了用而用”。
小项目的话,简单方案最好;不需要用太复杂的。
结合框架特性:如Spring已内置大量模式支持(IoC、AOP),避免重复造轮子。
代码可读性很重要,模式名和注释得清楚,好让团队一起工作。