Spring中都应用了哪些设计模式?
好的!以下是您提到的八种设计模式在 Spring 中的简单示例:
1. 简单工厂模式
简单工厂模式通过传入参数来决定实例化哪个类。Spring 中的 BeanFactory
就是简单工厂模式的应用。
示例代码:
// 1. 创建接口和具体实现类
public interface Animal {
void speak();
}
public class Dog implements Animal {
@Override
public void speak() {
System.out.println("Woof!");
}
}
public class Cat implements Animal {
@Override
public 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 {
@Override
public void doSomething() {
System.out.println("ConcreteProductA is doing something.");
}
}
// 3. 工厂方法
public abstract class Creator {
public abstract Product factoryMethod();
}
public class ConcreteCreatorA extends Creator {
@Override
public 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 {
@Override
public void serve() {
System.out.println("Service is serving...");
}
}
public class ProxyHandler implements InvocationHandler {
private final Object target;
public ProxyHandler(Object target) {
this.target = target;
}
@Override
public 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 {
@Override
public String make() {
return "Simple Coffee";
}
}
public class MilkDecorator implements Coffee {
private final Coffee coffee;
public MilkDecorator(Coffee coffee) {
this.coffee = coffee;
}
@Override
public String make() {
return coffee.make() + " + Milk";
}
}
public class SugarDecorator implements Coffee {
private final Coffee coffee;
public SugarDecorator(Coffee coffee) {
this.coffee = coffee;
}
@Override
public 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 Coffee
coffee = new MilkDecorator(coffee);
System.out.println(coffee.make()); // 输出: Simple Coffee + Milk
coffee = 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;
}
@Override
public 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 {
@Override
public void execute() {
System.out.println("Executing Strategy A");
}
}
class ConcreteStrategyB implements Strategy {
@Override
public 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 A
Context 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 {
@Override
protected void step1() {
System.out.println("Step 1");
}
@Override
protected 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 提供了高度的灵活性和可扩展性,帮助开发者实现松耦合和高内聚的代码结构。