Backend Development 9 min read

Common Spring Design Patterns: Simple Factory, Factory Method, Singleton, Adapter, Decorator, Proxy, Observer, Strategy, and Template Method

This article explains how Spring implements nine classic design patterns—including Simple Factory, Factory Method, Singleton, Adapter, Decorator, Proxy, Observer, Strategy, and Template Method—through configuration examples and Java code, illustrating their roles in building flexible, maintainable backend applications.

Java Captain
Java Captain
Java Captain
Common Spring Design Patterns: Simple Factory, Factory Method, Singleton, Adapter, Decorator, Proxy, Observer, Strategy, and Template Method

Design patterns are essential references for developers, and Spring, as a leading Java framework, provides concrete implementations of many classic patterns that improve architecture and code quality.

Simple Factory Pattern : Spring's <bean> definitions act as a simple factory, where a factory class creates product instances based on a given identifier. Example XML configuration creates two beans, singletonBean and itxxzBean , each instantiated via constructor arguments.

<beans>
  <bean id="singletonBean" class="com.itxxz.HelloItxxz">
    <constructor-arg>
      <value>Hello! 这是singletonBean!value</value>
    </constructor-arg>
  </bean>
  <bean id="itxxzBean" class="com.itxxz.HelloItxxz" singleton="false">
    <constructor-arg>
      <value>Hello! 这是itxxzBean! value</value>
    </constructor-arg>
  </bean>
</beans>

Factory Method Pattern : By defining a static factory method in a Java class and referencing it with factory-method in XML, Spring can delegate object creation to that method. The following Java class provides createRandom() , and the XML bean uses factory-method="createRandom" with prototype scope.

import java.util.Random;
public class StaticFactoryBean {
    public static Integer createRandom() {
        return new Integer(new Random().nextInt());
    }
}
<bean id="random" class="example.chapter3.StaticFactoryBean" factory-method="createRandom" scope="prototype"/>

Test code demonstrates retrieving the bean from XmlBeanFactory and printing the generated random number.

public static void main(String[] args) {
    // getBean() returns a random number; without factory-method it would return the factory bean itself
    XmlBeanFactory factory = new XmlBeanFactory(new ClassPathResource("config.xml"));
    System.out.println("我是IT学习者创建的实例:" + factory.getBean("random").toString());
}

Singleton Pattern : Spring beans are singleton by default, providing a global access point via the BeanFactory. The singleton attribute or scope can override this behavior.

Adapter Pattern : In Spring AOP, Advice objects are adapted to MethodInterceptor implementations. The example shows the AdvisorAdapter interface and a MethodBeforeAdviceAdapter class that adapts MethodBeforeAdvice to an interceptor.

public interface AdvisorAdapter {
    boolean supportsAdvice(Advice advice);
    MethodInterceptor getInterceptor(Advisor advisor);
}

public class MethodBeforeAdviceAdapter implements AdvisorAdapter, Serializable {
    public boolean supportsAdvice(Advice advice) {
        return advice instanceof MethodBeforeAdvice;
    }
    public MethodInterceptor getInterceptor(Advisor advisor) {
        MethodBeforeAdvice advice = (MethodBeforeAdvice) advisor.getAdvice();
        return new MethodBeforeAdviceInterceptor(advice);
    }
}

Decorator (Wrapper) Pattern : When an application must switch among multiple data sources at runtime, Spring can define several DataSource beans and dynamically set the appropriate one on the SessionFactory , effectively decorating the session with different responsibilities.

Proxy Pattern : Spring creates proxy objects (e.g., JdkDynamicAopProxy , Cglib2AopProxy ) to control access to target beans, enabling method interception without altering the original class.

Observer Pattern : Spring’s event mechanism (e.g., ApplicationListener ) follows the observer pattern, notifying registered listeners when an application event occurs.

Strategy Pattern : Spring uses strategy objects for bean instantiation; the SimpleInstantiationStrategy class selects an appropriate algorithm at runtime, illustrating the pattern’s flexibility.

Template Method Pattern : While traditionally implemented via inheritance, Spring’s JdbcTemplate demonstrates a callback‑based approach where the invariant algorithm resides in the template method, and client‑provided callbacks supply the variable parts.

The article concludes with visual illustrations of these patterns within the Spring framework.

Design PatternsJavabackend developmentSpringsingletonAdapterFactory Method
Java Captain
Written by

Java Captain

Focused on Java technologies: SSM, the Spring ecosystem, microservices, MySQL, MyCat, clustering, distributed systems, middleware, Linux, networking, multithreading; occasionally covers DevOps tools like Jenkins, Nexus, Docker, ELK; shares practical tech insights and is dedicated to full‑stack Java development.

0 followers
Reader feedback

How this landed with the community

login Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.