当前位置: 首页 > news >正文

Spring中都应用了哪些设计模式?

好的!以下是您提到的八种设计模式在 Spring 中的简单示例:

1. 简单工厂模式

简单工厂模式通过传入参数来决定实例化哪个类。Spring 中的 BeanFactory 就是简单工厂模式的应用。

示例代码:
// 1. 创建接口和具体实现类
public interface Animal {void speak();
}public class Dog implements Animal {@Overridepublic void speak() {System.out.println("Woof!");}
}public class Cat implements Animal {@Overridepublic void speak() {System.out.println("Meow!");}
}// 2. 工厂类,传入参数决定实例化哪个类
public class AnimalFactory {public static Animal getAnimal(String animalType) {if ("dog".equalsIgnoreCase(animalType)) {return new Dog();} else if ("cat".equalsIgnoreCase(animalType)) {return new Cat();}return null;}
}// 3. 使用工厂类创建实例
public class FactoryPatternDemo {public static void main(String[] args) {Animal dog = AnimalFactory.getAnimal("dog");dog.speak(); // 输出: Woof!Animal cat = AnimalFactory.getAnimal("cat");cat.speak(); // 输出: Meow!}
}

2. 工厂方法模式

工厂方法模式定义一个方法用于创建对象,由子类决定实例化哪一个类。Spring 使用 FactoryBean 来实现这个模式。

示例代码:
// 1. 定义接口
public interface Product {void doSomething();
}// 2. 具体实现
public class ConcreteProductA implements Product {@Overridepublic void doSomething() {System.out.println("ConcreteProductA is doing something.");}
}// 3. 工厂方法
public abstract class Creator {public abstract Product factoryMethod();
}public class ConcreteCreatorA extends Creator {@Overridepublic Product factoryMethod() {return new ConcreteProductA();}
}// 4. 使用工厂方法
public class FactoryMethodDemo {public static void main(String[] args) {Creator creator = new ConcreteCreatorA();Product product = creator.factoryMethod();product.doSomething(); // 输出: ConcreteProductA is doing something.}
}

3. 单例模式

Spring 中的 Singleton 模式使用了双重检查锁定的方式来确保只有一个实例。

示例代码:
public class Singleton {private static volatile Singleton instance;private Singleton() {}public static Singleton getInstance() {if (instance == null) {synchronized (Singleton.class) {if (instance == null) {instance = new Singleton();}}}return instance;}
}public class SingletonDemo {public static void main(String[] args) {Singleton singleton = Singleton.getInstance();System.out.println(singleton);}
}

4. 代理模式

Spring AOP 是通过代理模式来增强对象的功能。Spring 提供了 JDK 动态代理和 CGLIB 代理。

示例代码(使用 JDK 动态代理):
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;public interface Service {void serve();
}public class ServiceImpl implements Service {@Overridepublic void serve() {System.out.println("Service is serving...");}
}public class ProxyHandler implements InvocationHandler {private final Object target;public ProxyHandler(Object target) {this.target = target;}@Overridepublic Object invoke(Object proxy, Method method, Object[] args) throws Throwable {System.out.println("Before method call...");Object result = method.invoke(target, args);System.out.println("After method call...");return result;}
}public class ProxyPatternDemo {public static void main(String[] args) {Service service = new ServiceImpl();Service proxy = (Service) Proxy.newProxyInstance(Service.class.getClassLoader(),new Class[]{Service.class},new ProxyHandler(service));proxy.serve(); // 输出: Before method call... Service is serving... After method call...}
}

5. 装饰器模式

装饰器模式动态地给一个对象添加一些额外的功能。Spring 中的 DataSource 装饰模式就是这个例子。

示例代码:
public interface Coffee {String make();
}public class SimpleCoffee implements Coffee {@Overridepublic String make() {return "Simple Coffee";}
}public class MilkDecorator implements Coffee {private final Coffee coffee;public MilkDecorator(Coffee coffee) {this.coffee = coffee;}@Overridepublic String make() {return coffee.make() + " + Milk";}
}public class SugarDecorator implements Coffee {private final Coffee coffee;public SugarDecorator(Coffee coffee) {this.coffee = coffee;}@Overridepublic String make() {return coffee.make() + " + Sugar";}
}public class DecoratorPatternDemo {public static void main(String[] args) {Coffee coffee = new SimpleCoffee();System.out.println(coffee.make()); // 输出: Simple Coffeecoffee = new MilkDecorator(coffee);System.out.println(coffee.make()); // 输出: Simple Coffee + Milkcoffee = new SugarDecorator(coffee);System.out.println(coffee.make()); // 输出: Simple Coffee + Milk + Sugar}
}

6. 观察者模式

观察者模式用于一对多的依赖关系,Spring 中的事件监听器使用了这个模式。

示例代码:
import java.util.ArrayList;
import java.util.List;interface Observer {void update(String message);
}class ConcreteObserver implements Observer {private String name;public ConcreteObserver(String name) {this.name = name;}@Overridepublic void update(String message) {System.out.println(name + " received message: " + message);}
}class Subject {private List<Observer> observers = new ArrayList<>();public void addObserver(Observer observer) {observers.add(observer);}public void removeObserver(Observer observer) {observers.remove(observer);}public void notifyObservers(String message) {for (Observer observer : observers) {observer.update(message);}}
}public class ObserverPatternDemo {public static void main(String[] args) {Subject subject = new Subject();Observer observer1 = new ConcreteObserver("Observer 1");Observer observer2 = new ConcreteObserver("Observer 2");subject.addObserver(observer1);subject.addObserver(observer2);subject.notifyObservers("Hello Observers!"); // 输出: Observer 1 received message: Hello Observers!// 输出: Observer 2 received message: Hello Observers!}
}

7. 策略模式

策略模式允许在运行时选择算法。Spring 中的 HandlerMapping 使用了策略模式来根据请求映射到不同的处理器。

示例代码:
interface Strategy {void execute();
}class ConcreteStrategyA implements Strategy {@Overridepublic void execute() {System.out.println("Executing Strategy A");}
}class ConcreteStrategyB implements Strategy {@Overridepublic void execute() {System.out.println("Executing Strategy B");}
}class Context {private final Strategy strategy;public Context(Strategy strategy) {this.strategy = strategy;}public void executeStrategy() {strategy.execute();}
}public class StrategyPatternDemo {public static void main(String[] args) {Context contextA = new Context(new ConcreteStrategyA());contextA.executeStrategy(); // 输出: Executing Strategy AContext contextB = new Context(new ConcreteStrategyB());contextB.executeStrategy(); // 输出: Executing Strategy B}
}

8. 模板方法模式

模板方法模式定义了一个操作中的步骤,并允许子类在不改变操作结构的情况下实现某些步骤。

示例代码:
abstract class AbstractTemplate {public void templateMethod() {step1();step2();}protected abstract void step1();protected abstract void step2();
}class ConcreteClass extends AbstractTemplate {@Overrideprotected void step1() {System.out.println("Step 1");}@Overrideprotected void step2() {System.out.println("Step 2");}
}public class TemplateMethodPatternDemo {public static void main(String[] args) {AbstractTemplate template = new ConcreteClass();template.templateMethod();}
}

以上示例演示了 Spring 中常见的 8 种设计模式的应用。通过这些设计模式,Spring 提供了高度的灵活性和可扩展性,帮助开发者实现松耦合和高内聚的代码结构。

http://www.lryc.cn/news/535059.html

相关文章:

  • VSCode的安裝以及使用
  • Datawhale 组队学习 Ollama教程 task1
  • 前端技术学习——ES6核心基础
  • 《DeepSeek技术应用与赋能运营商办公提效案例实操落地课程》
  • STM32-知识
  • 线程同步(互斥锁与条件变量)
  • Ubuntu指令学习(个人记录、偶尔更新)
  • Visual Studio 进行单元测试【入门】
  • 【经验分享】Linux 系统安装后内核参数优化
  • linux统计文件夹下有多少个.rst文件行数小于4行
  • 使用开源项目xxl-cache构建多级缓存
  • LVDS接口总结--(5)IDELAY3仿真
  • Vue3(1)
  • 玩转适配器模式
  • 2.11寒假作业
  • untiy 冰面与地面,物理材质的影响
  • 视频编解码标准中的 Profile 和 Level
  • 通用的将jar制作成docker镜像sh脚本
  • AUTOGPT:基于GPT模型开发的实验性开源应用程序; 目标设定与分解 ;;自主思考与决策 ;;信息交互与执行
  • 异步线程中使用RestTemplate注入空指针解决
  • 2024BaseCTF_week4_web上
  • 说一下 jvm 有哪些垃圾回收器?
  • react国际化配置react-i18next详解
  • Java并发编程——上下文切换、死锁、资源限制
  • MS08067练武场--WP
  • ubuntu文件同步
  • C++23 新特性解析
  • 算法05-堆排序
  • Arrays工具类详解
  • 无人机图像拼接数据的可视化与制图技术:以植被监测为例