以下是针对上述设计模式在 Spring Boot 中的应用举例,并给出相应的代码示例:1. 单例模式(Singleton Pattern):
- 比喻:如同公司只有一个财务部门,所有与财务相关的事务都由这个唯一的部门处理。
- 代码示例:假设在 Spring Boot 中有一个配置类,用于全局配置某些属性,如 `AppConfig` 类。
@Configuration
public class AppConfig {
private static AppConfig instance;
private AppConfig() {}
public static AppConfig getInstance() {
if (instance == null) {
instance = new AppConfig();
}
return instance;
}
// 配置属性和方法
}
- Spring Boot 中的应用场景:通常用于一些全局共享且只需一个实例的配置或服务。2. 工厂模式(Factory Pattern):
- 比喻:类似于一个生产不同类型玩具的工厂,根据订单需求生产特定的玩具。
- 代码示例:假设创建不同类型的数据源。
@Component
public class DataSourceFactory {
public DataSource createDataSource(String type) {
if ("mysql".equals(type)) {
// 创建并返回 MySQL 数据源
return new MysqlDataSource();
} else if ("oracle".equals(type)) {
// 创建并返回 Oracle 数据源
return new OracleDataSource();
}
return null;
}
}
- Spring Boot 中的应用场景:创建各种 Bean 对象,根据条件或配置返回不同的实例。3. 代理模式(Proxy Pattern):
- 比喻:好比明星的经纪人替明星处理一些事务,过滤不必要的干扰。
- 代码示例:使用 Spring AOP 实现方法的事务管理。
@Service
public class UserService {
@Transactional
public void saveUser(User user) {
// 保存用户的业务逻辑
}
}
- Spring Boot 中的应用场景:Spring AOP 自动为添加 `@Transactional` 注解的方法创建代理,实现事务的开启、提交和回滚。4. 观察者模式(Observer Pattern):
- 比喻:就像一个新闻发布系统,有众多的订阅者等待接收新的新闻。
- 代码示例:自定义事件的发布和监听。
@Component
public class CustomEventPublisher {
@Autowired
private ApplicationEventPublisher eventPublisher;
public void publishEvent(String message) {
CustomEvent event = new CustomEvent(this, message);
eventPublisher.publishEvent(event);
}
}
@Component
public class CustomEventListener {
@EventListener
public void handleCustomEvent(CustomEvent event) {
System.out.println("Received custom event: " + event.getMessage());
}
}
class CustomEvent extends ApplicationEvent {
private String message;
public CustomEvent(Object source, String message) {
super(source);
this.message = message;
}
public String getMessage() {
return message;
}
}
- Spring Boot 中的应用场景:`@EventListener` 注解用于监听自定义事件或框架内置事件。5. 模板方法模式(Template Method Pattern):
- 比喻:如同制作蛋糕的通用流程,每个步骤都固定,但具体细节(如配料、装饰)可以变化。
- 代码示例:假设在数据访问层有一个通用的操作模板。
public abstract class AbstractDao<T> {
public void save(T entity) {
beginTransaction();
doSave(entity);
commitTransaction();
}
protected abstract void doSave(T entity);
protected void beginTransaction() {
// 开始事务的通用逻辑
}
protected void commitTransaction() {
// 提交事务的通用逻辑
}
}
@Repository
public class UserDao extends AbstractDao<User> {
@Override
protected void doSave(User user) {
// 具体的保存用户的逻辑
}
}
- Spring Boot 中的应用场景:`JdbcTemplate` 中的一些方法就是模板方法模式的应用。6. 策略模式(Strategy Pattern):
- 比喻:好比出行时根据不同情况选择不同的交通工具(步行、骑车、开车)。
- 代码示例:假设根据不同的条件选择不同的缓存策略。
interface CacheStrategy {
void put(String key, Object value);
Object get(String key);
}
class LocalCacheStrategy implements CacheStrategy {
@Override
public void put(String key, Object value) {
// 本地缓存的实现
}
@Override
public Object get(String key) {
// 本地缓存的获取
}
}
class RedisCacheStrategy implements CacheStrategy {
@Override
public void put(String key, Object value) {
// Redis 缓存的实现
}
@Override
public Object get(String key) {
// Redis 缓存的获取
}
}
@Component
public class CacheService {
private CacheStrategy cacheStrategy;
public CacheService(CacheStrategy cacheStrategy) {
this.cacheStrategy = cacheStrategy;
}
public void setCacheStrategy(CacheStrategy cacheStrategy) {
this.cacheStrategy = cacheStrategy;
}
public void put(String key, Object value) {
cacheStrategy.put(key, value);
}
public Object get(String key) {
return cacheStrategy.get(key);
}
}
- Spring Boot 中的应用场景:在不同条件下选择不同的缓存实现、消息发送方式等。7. 责任链模式(Chain of Responsibility Pattern):
- 比喻:就像一个审批流程,依次经过多个审批人员,直到有人批准或拒绝。
- 代码示例:假设在请求处理中有多个处理器组成责任链。
interface Handler {
void handleRequest(Request request);
}
class HandlerA implements Handler {
private Handler nextHandler;
@Override
public void handleRequest(Request request) {
if (request.getPriority() == 1) {
// 处理请求
} else if (nextHandler!= null) {
nextHandler.handleRequest(request);
}
}
public void setNextHandler(Handler nextHandler) {
this.nextHandler = nextHandler;
}
}
class HandlerB implements Handler {
private Handler nextHandler;
@Override
public void handleRequest(Request request) {
if (request.getPriority() == 2) {
// 处理请求
} else if (nextHandler!= null) {
nextHandler.handleRequest(request);
}
}
public void setNextHandler(Handler nextHandler) {
this.nextHandler = nextHandler;
}
}
class Request {
private int priority;
// 构造函数、getter 和 setter 方法
}
- Spring Boot 中的应用场景:在请求处理、权限验证等流程中,多个处理器依次处理请求。