Spring Boot应用程序中的设计模式
在Spring Boot应用程序中使用各种设计模式是提高代码质量和可维护性的常见做法。这里,我将介绍几种设计模式,并提供一些简单的代码示例来说明它们在Spring Boot中的应用。
1. 单例模式 (Singleton Pattern)
单例模式确保类只有一个实例,并提供一个全局访问点。
@Component
public class SingletonService {
private static SingletonService instance;
private SingletonService() {}
public static synchronized SingletonService getInstance() {
if (instance == null) {
instance = new SingletonService();
}
return instance;
}
}
2. 工厂模式 (Factory Pattern)
工厂模式用于创建对象,允许接口指定对象的类型,但由子类决定实例化哪个类。
public interface PaymentService {
void processPayment();
}
@Service
public class PaymentServiceFactory {
public PaymentService getPaymentService(String type) {
if ("credit".equals(type)) {
return new CreditCardPaymentService();
} else if ("paypal".equals(type)) {
return new PayPalPaymentService();
}
throw new IllegalArgumentException("Unknown payment type: " + type);
}
}
@Component
public class CreditCardPaymentService implements PaymentService {
@Override
public void processPayment() {
// 信用卡支付逻辑
}
}
@Component
public class PayPalPaymentService implements PaymentService {
@Override
public void processPayment() {
// PayPal支付逻辑
}
}
3. 策略模式 (Strategy Pattern)
策略模式定义了一系列算法,并将每个算法封装起来,使它们可以互换。
public interface SortingStrategy {
void sort(List<Integer> numbers);
}
@Component
public class QuickSortStrategy implements SortingStrategy {
@Override
public void sort(List<Integer> numbers) {
// 快速排序实现
}
}
@Component
public class MergeSortStrategy implements SortingStrategy {
@Override
public void sort(List<Integer> numbers) {
// 归并排序实现
}
}
@Service
public class SortingService {
private SortingStrategy sortingStrategy;
public void setSortingStrategy(SortingStrategy sortingStrategy) {
this.sortingStrategy = sortingStrategy;
}
public void sortNumbers(List<Integer> numbers) {
sortingStrategy.sort(numbers);
}
}
4. 观察者模式 (Observer Pattern)
观察者模式用于建立一个对象(主题)与多个观察者之间的依赖关系,当主题状态改变时,所有观察者都会被通知。
public interface OrderObserver {
void notify(Order order);
}
@Service
public class EmailService implements OrderObserver {
@Override
public void notify(Order order) {
// 发送订单状态更新的电子邮件
}
}
@Service
public class OrderService {
private List<OrderObserver> observers = new ArrayList<>();
public void attachObserver(OrderObserver observer) {
observers.add(observer);
}
public void changeOrderStatus(Order order, String status) {
// 更新订单状态的逻辑
notifyAllObservers(order);
}
private void notifyAllObservers(Order order) {
for (OrderObserver observer : observers) {
observer.notify(order);
}
}
}
5. 装饰器模式 (Decorator Pattern)
装饰器模式允许向一个现有的对象添加新的功能,而不改变其结构。
public interface Coffee {
String getDescription();
double getCost();
}
public class SimpleCoffee implements Coffee {
@Override
public String getDescription() {
return "Simple Coffee";
}
@Override
public double getCost() {
return 2.0;
}
}
public abstract class CoffeeDecorator implements Coffee {
protected final Coffee decoratedCoffee;
public CoffeeDecorator(Coffee coffee) {
this.decoratedCoffee = coffee;
}
public String getDescription() {
return decoratedCoffee.getDescription();
}
public double getCost() {
return decoratedCoffee.getCost();
}
}
public class MilkCoffeeDecorator extends CoffeeDecorator {
public MilkCoffeeDecorator(Coffee coffee) {
super(coffee);
}
@Override
public String getDescription() {
return super.getDescription() + ", with milk";
}
@Override
public double getCost() {
return super.getCost() + 0.5;
}
}
6. 代理模式 (Proxy Pattern)
代理模式为另一个对象提供一个替身或占位符,以控制对这个对象的访问。
public interface PaymentProcessor {
void processPayment(int amount);
}
public class RealPaymentProcessor implements PaymentProcessor {
@Override
public void processPayment(int amount) {
// 实际处理支付
}
}
public class PaymentProcessorProxy implements PaymentProcessor {
private RealPaymentProcessor realPaymentProcessor;
@Override
public void processPayment(int amount) {
if (realPaymentProcessor == null) {
realPaymentProcessor = new RealPaymentProcessor();
}
// 在调用实际支付处理器之前进行一些检查或日志记录
realPaymentProcessor.processPayment(amount);
}
}
7. 建造者模式 (Builder Pattern)
建造者模式用于构造复杂的对象,允许通过指定它们的类型和内容来逐步构造对象。
public class User {
private final String name;
private final int age;
private final String address;
private User(UserBuilder builder) {
this.name = builder.name;
this.age = builder.age;
this.address = builder.address;
}
public static class UserBuilder {
private String name;
private int age;
private String address;
public UserBuilder setName(String name) {
this.name = name;
return this;
}
public UserBuilder setAge(int age) {
this.age = age;
return this;
}
public UserBuilder setAddress(String address) {
this.address = address;
return this;
}
public User build() {
return new User(this);
}
}
}
8. 适配器模式 (Adapter Pattern)
适配器模式允许不兼容的接口一起工作,它将一个类的接口转换成客户期望的另一个接口。
public interface AdvancedMediaPlayer {
void playVlc(String fileName);
void playMp4(String fileName);
}
public class VlcPlayer implements AdvancedMediaPlayer {
@Override
public void playVlc(String fileName) {
// 播放VLC格式
}
@Override
public void playMp4(String fileName) {
// 不做任何操作
}
}
public class MediaAdapter implements MediaPlayer {
private AdvancedMediaPlayer advancedMusicPlayer;
public MediaAdapter(String audioType) {
if (audioType.equalsIgnoreCase("vlc")) {
advancedMusicPlayer = new VlcPlayer();
}
}
@Override
public void play(String audioType, String fileName) {
if (audioType.equalsIgnoreCase("vlc")) {
advancedMusicPlayer.playVlc(fileName);
}
}
}
9. 桥接模式 (Bridge Pattern)
桥接模式用于将抽象部分与它的实现部分分离,使它们可以独立地变化。
public interface Color {
String applyColor();
}
public abstract class Shape {
protected Color color;
public Shape(Color color) {
this.color = color;
}
abstract public String draw();
}
public class Circle extends Shape {
public Circle(Color color) {
super(color);
}
@Override
public String draw() {
return "Circle drawn with " + color.applyColor();
}
}
public class RedColor implements Color {
@Override
public String applyColor() {
return "red";
}
}
10. 命令模式 (Command Pattern)
命令模式用于将请求封装为一个对象,从而允许用户根据不同的请求、队列或日志请求以及支持可撤销的操作。
public interface Command {
void execute();
}
public class Light {
public void turnOn() {
System.out.println("Light is on");
}
public void turnOff() {
System.out.println("Light is off");
}
}
public class TurnOnCommand implements Command {
private Light light;
public TurnOnCommand(Light light) {
this.light = light;
}
@Override
public void execute() {
light.turnOn();
}
}
public class RemoteControl {
private Command command;
public void setCommand(Command command) {
this.command = command;
}
public void pressButton() {
command.execute();
}
}
11. 状态模式 (State Pattern)
状态模式允许一个对象在其内部状态改变时改变它的行为,对象看起来似乎修改了它的类。
public interface State {
void doAction(Context context);
}
public class StartState implements State {
@Override
public void doAction(Context context) {
System.out.println("Player is in start state");
context.setState(this);
}
public String toString(){
return "Start State";
}
}
public class StopState implements State {
@Override
public void doAction(Context context) {
System.out.println("Player is in stop state");
context.setState(this);
}
public String toString(){
return "Stop State";
}
}
public class Context {
private State state;
public Context() {
state = null;
}
public void setState(State state) {
this.state = state;
}
public State getState() {
return state;
}
}
12. 模板方法模式 (Template Method Pattern)
模板方法模式定义了一个算法的骨架,并允许子类为一个或多个步骤提供实现。
public abstract class Game {
abstract void initialize();
abstract void startPlay();
abstract void endPlay();
// 模板方法
public final void play() {
initialize();
startPlay();
endPlay();
}
}
public class Cricket extends Game {
@Override
void initialize() {
System.out.println("Cricket Game Initialized! Start playing.");
}
@Override
void startPlay() {
System.out.println("Cricket Game Started. Enjoy the game!");
}
@Override
void endPlay() {
System.out.println("Cricket Game Finished!");
}
}
13. 责任链模式 (Chain of Responsibility Pattern)
责任链模式用于将请求的发送者和接收者解耦,允许多个对象处理请求。请求沿着责任链传递,直到被处理。
public abstract class Logger {
public static int INFO = 1;
public static int DEBUG = 2;
public static int ERROR = 3;
protected int level;
// 责任链中的下一个元素
protected Logger nextLogger;
public void setNextLogger(Logger nextLogger) {
this.nextLogger = nextLogger;
}
public void logMessage(int level, String message) {
if (this.level <= level) {
write(message);
}
if (nextLogger != null) {
nextLogger.logMessage(level, message);
}
}
abstract protected void write(String message);
}
public class ConsoleLogger extends Logger {
public ConsoleLogger(int level) {
this.level = level;
}
@Override
protected void write(String message) {
System.out.println("Standard Console::Logger: " + message);
}
}
14. 迭代器模式 (Iterator Pattern)
迭代器模式用于顺序访问集合对象的元素,不需要知道集合对象的底层表示。
public interface Iterator {
boolean hasNext();
Object next();
}
public interface Container {
Iterator getIterator();
}
public class NameRepository implements Container {
public String names[] = {"John", "Jane", "Lily", "Mike"};
@Override
public Iterator getIterator() {
return new NameIterator();
}
private class NameIterator implements Iterator {
int index;
@Override
public boolean hasNext() {
return index < names.length;
}
@Override
public Object next() {
if (this.hasNext()) {
return names[index++];
}
return null;
}
}
}
15. 访问者模式 (Visitor Pattern)
访问者模式用于操作一组对象,允许在不改变这些对象的类的情况下定义新的操作。
public interface ComputerPart {
void accept(ComputerPartVisitor computerPartVisitor);
}
public interface ComputerPartVisitor {
void visit(Computer computer);
void visit(Mouse mouse);
void visit(Keyboard keyboard);
void visit(Monitor monitor);
}
public class Computer implements ComputerPart {
ComputerPart[] parts;
public Computer() {
parts = new ComputerPart[] {new Mouse(), new Keyboard(), new Monitor()};
}
@Override
public void accept(ComputerPartVisitor computerPartVisitor) {
for (int i = 0; i < parts.length; i++) {
parts[i].accept(computerPartVisitor);
}
computerPartVisitor.visit(this);
}
}
这些设计模式在Spring Boot应用中的使用可以增强代码的灵活性、可维护性和可扩展性。根据应用程序的需求和上下文选择合适的设计模式是至关重要的。
转载自:https://juejin.cn/post/7313768894589026330