Design Patterns Used in MyBatis Source Code
This article examines how MyBatis implements numerous classic design patterns—including Builder, Factory, Singleton, Proxy, Composite, Template Method, Adapter, Decorator, and Iterator—through its source code, explaining each pattern's role, related classes, and code examples to deepen developers' understanding of backend architecture.
The article explores the practical application of 26 classic design patterns within the MyBatis framework, demonstrating how reading the source code can deepen developers' grasp of these patterns beyond theoretical concepts.
MyBatis employs the Builder pattern in classes such as SqlSessionFactoryBuilder , XMLConfigBuilder , and XMLMapperBuilder to construct complex objects like Configuration and SqlSessionFactory through a series of build* methods.
Factory pattern examples include SqlSessionFactory , ObjectFactory , and MapperProxyFactory , which encapsulate object creation logic and return appropriate instances based on input parameters.
Singleton pattern is used for ErrorContext (thread‑local singleton) and LogFactory , ensuring a single shared instance per JVM or per thread.
Proxy pattern forms the core of MyBatis: MapperProxy implements InvocationHandler to intercept mapper method calls, delegating execution to SqlSession and the underlying Executor .
Composite pattern appears in the SQL node hierarchy (e.g., SqlNode and its subclasses like ChooseSqlNode ), allowing tree‑like composition of SQL fragments.
Template Method pattern is evident in BaseExecutor , which defines the overall execution flow while abstract methods such as doUpdate , doQuery , and doFlushStatements are implemented by concrete executors ( SimpleExecutor , ReuseExecutor , BatchExecutor ).
Adapter pattern is used to adapt MyBatis logging to various logging frameworks via the Log interface and its implementations (e.g., Log4jImpl , Slf4jImpl ).
Decorator pattern decorates the core cache ( PerpetualCache ) with additional responsibilities such as LRU, FIFO, logging, serialization, and synchronization, forming a chain like SynchronizedCache → LoggingCache → SerializedCache → ScheduledCache → LruCache → PerpetualCache .
Iterator pattern is implemented by PropertyTokenizer , which parses property strings and provides hasNext and next methods to iterate over nested property segments.
Throughout the article, representative code snippets are shown to illustrate each pattern’s concrete implementation within MyBatis.
Architecture Digest
Focusing on Java backend development, covering application architecture from top-tier internet companies (high availability, high performance, high stability), big data, machine learning, Java architecture, and other popular fields.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.