Spring框架中几种常见的设计模式

1. 单例模式(Singleton Pattern)

业务场景

单例模式在需要确保一个对象的唯一性和全局访问时非常有用,例如数据库连接池、缓存、日志记录器等。

示例代码

  • 定义单例 Bean(默认就是单例模式):

    @Component
    public class DatabaseConnection {
        private Connection connection;
    
        public DatabaseConnection() {
            // 初始化数据库连接
        }
    
        public Connection getConnection() {
            return connection;
        }
    }
    
  • 使用单例 Bean

    @Component
    public class SomeService {
        private final DatabaseConnection databaseConnection;
    
        @Autowired
        public SomeService(DatabaseConnection databaseConnection) {
            this.databaseConnection = databaseConnection;
        }
    
        public void useConnection() {
            Connection connection = databaseConnection.getConnection();
            // 使用连接
        }
    }
    

2. 工厂模式(Factory Pattern)

业务场景

工厂模式适用于对象创建过程复杂且需要条件控制时。例如,根据配置文件创建不同类型的对象。

示例代码

  • 定义工厂类

    @Component
    public class BeanFactory {
        public MyBean createBean(String type) {
            switch (type) {
                case "type1":
                    return new MyBeanType1();
                case "type2":
                    return new MyBeanType2();
                default:
                    throw new IllegalArgumentException("Unknown type: " + type);
            }
        }
    }
    
  • 使用工厂类

    @Component
    public class SomeService {
        private final BeanFactory beanFactory;
    
        @Autowired
        public SomeService(BeanFactory beanFactory) {
            this.beanFactory = beanFactory;
        }
    
        public void performOperation(String type) {
            MyBean myBean = beanFactory.createBean(type);
            myBean.doSomething();
        }
    }
    

3. 代理模式(Proxy Pattern)

业务场景

代理模式在需要为对象的某些功能添加额外的行为时使用,如权限控制、日志记录、事务管理等。

示例代码

  • 定义切面

    @Aspect
    @Component
    public class LoggingAspect {
        @Before("execution(* com.example.service.*.*(..))")
        public void logBefore(JoinPoint joinPoint) {
            System.out.println("Executing method: " + joinPoint.getSignature().getName());
        }
    }
    
  • 配置切面

    @Configuration
    @EnableAspectJAutoProxy
    public class AppConfig {
        @Bean
        public LoggingAspect loggingAspect() {
            return new LoggingAspect();
        }
    }
    

4. 模板方法模式(Template Method Pattern)

业务场景

模板方法模式适用于有固定算法步骤,但某些步骤需要由子类实现时,如数据访问操作、文件处理等。

示例代码

  • 定义模板类

    public abstract class DataProcessor {
        public void process() {
            readData();
            processData();
            writeData();
        }
    
        protected abstract void readData();
        protected abstract void processData();
        protected abstract void writeData();
    }
    
  • 子类实现

    @Component
    public class CsvDataProcessor extends DataProcessor {
        @Override
        protected void readData() {
            // 读取CSV数据
        }
    
        @Override
        protected void processData() {
            // 处理数据
        }
    
        @Override
        protected void writeData() {
            // 写入数据
        }
    }
    
  • 使用模板类

    @Component
    public class SomeService {
        private final DataProcessor dataProcessor;
    
        @Autowired
        public SomeService(DataProcessor dataProcessor) {
            this.dataProcessor = dataProcessor;
        }
    
        public void execute() {
            dataProcessor.process();
        }
    }
    

5. 观察者模式(Observer Pattern)

业务场景

观察者模式适用于一个对象的状态变化需要通知其他多个对象时,如事件发布与订阅系统。

示例代码

  • 定义事件

    public class CustomEvent extends ApplicationEvent {
        public CustomEvent(Object source) {
            super(source);
        }
    }
    
  • 事件发布器

    @Component
    public class CustomEventPublisher {
        @Autowired
        private ApplicationEventPublisher applicationEventPublisher;
    
        public void publishEvent() {
            CustomEvent customEvent = new CustomEvent(this);
            applicationEventPublisher.publishEvent(customEvent);
        }
    }
    
  • 事件监听器

    @Component
    public class CustomEventListener implements ApplicationListener<CustomEvent> {
        @Override
        public void onApplicationEvent(CustomEvent event) {
            System.out.println("Received custom event - " + event.getSource());
        }
    }
    

6. 依赖注入模式(Dependency Injection Pattern)

业务场景

依赖注入模式适用于增强代码的可测试性和模块化,通过外部配置注入依赖对象。

示例代码

  • 定义服务和存储库
    @Component
    public class MyService {
        private final MyRepository myRepository;
    
        @Autowired
        public MyService(MyRepository myRepository) {
            this.myRepository = myRepository;
        }
    
        public void performService() {
            myRepository.doSomething();
        }
    }
    
    @Component
    public class MyRepository {
        public void doSomething() {
            // 实现细节
        }
    }
    

7. 适配器模式(Adapter Pattern)

业务场景

适配器模式在需要将一个接口转换成另一个接口时使用,如集成第三方库。

示例代码

  • 定义适配器
    public interface NewService {
        void newMethod();
    }
    
    public class OldService {
        public void oldMethod() {
            // 旧方法实现
        }
    }
    
    @Component
    public class ServiceAdapter implements NewService {
        private final OldService oldService;
    
        @Autowired
        public ServiceAdapter(OldService oldService) {
            this.oldService = oldService;
        }
    
        @Override
        public void newMethod() {
            oldService.oldMethod();
        }
    }
    

8. 装饰器模式(Decorator Pattern)

业务场景

装饰器模式用于在不改变原类的情况下为类添加新的功能,如动态添加职责。

示例代码

  • 定义装饰器
    public interface Component {
        void operation();
    }
    
    @Component
    public class ConcreteComponent implements Component {
        @Override
        public void operation() {
            // 基本操作
        }
    }
    
    public abstract class Decorator implements Component {
        protected Component component;
    
        public Decorator(Component component) {
            this.component = component;
        }
    
        @Override
        public void operation() {
            component.operation();
        }
    }
    
    @Component
    public class ConcreteDecorator extends Decorator {
        @Autowired
        public ConcreteDecorator(Component component) {
            super(component);
        }
    
        @Override
        public void operation() {
            super.operation();
            // 额外操作
        }
    }
    

9. 策略模式(Strategy Pattern)

业务场景

策略模式在需要动态选择算法或行为时使用,如不同的支付方式、排序算法等。

示例代码

  • 定义策略接口

    public interface PaymentStrategy {
        void pay(int amount);
    }
    
    @Component
    public class CreditCardPayment implements PaymentStrategy {
        @Override
        public void pay(int amount) {
            // 信用卡支付实现
        }
    }
    
    @Component
    public class PayPalPayment implements PaymentStrategy {
        @Override
        public void pay(int amount) {
            // PayPal支付实现
        }
    }
    
  • 上下文类

    @Component
    public class PaymentContext {
        private PaymentStrategy paymentStrategy;
    
        @Autowired
        public void setPaymentStrategy(PaymentStrategy paymentStrategy) {
            this.paymentStrategy = paymentStrategy;
        }
    
        public void executePayment(int amount) {
            paymentStrategy.pay(amount);
        }
    }
    
  • 使用策略

    @Component
    public class SomeService {
        private final PaymentContext paymentContext;
    
        @Autowired
        public SomeService(PaymentContext paymentContext) {
            this.paymentContext = paymentContext;
        }
    
        public void performPayment(int amount) {
            paymentContext.executePayment(amount);
        }
    }
    

总结

以上详细介绍了 9 种常见的设计模式及其在 Spring 框架中的应用场景和示例代码。掌握这些设计模式可以帮助开发者更好地设计和实现代码,提高代码的可维护性和可扩展性。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值