夯实设计原则之合成复用原则

All Rights Reserved © jackiegu.cn

理念:

尽量使用对象组合,而不是继承来达到复用的目的;

合成复用原则就是在一个新的对象里通过关联关系(包括组合关系和聚合关系)来使用一些已有的对象,使之成为新对象的一部分;新对象通过委派调用已有对象的方法达到复用功能的目的;简言之:复用时要尽量使用组合/聚合关系,少用继承

案例:

这次小明已经完成了手上的工作,利用空闲时间来研究了一下MyBatis的源码;

阅读了DefaultSqlSessionFactory源码,如下:

/**
 * DefaultSqlSessionFactory实例与其configuration属性就是聚合关系实现
 */
public class DefaultSqlSessionFactory implements SqlSessionFactory {

    private final Configuration configuration;

  	public DefaultSqlSessionFactory(Configuration configuration) {
    	this.configuration = configuration;
  	}

  	@Override
  	public SqlSession openSession() {
    	return openSessionFromDataSource(configuration.getDefaultExecutorType(), null, false);
    }
    
    // ......
}

DefaultSqlSession源码,如下:

/**
 * DefaultSqlSession实例与其configuration属性就是聚合关系实现
 * DefaultSqlSession实例与其executor属性就是组合关系的实现
 */
public class DefaultSqlSession implements SqlSession {

  	private final Configuration configuration;
  	private final Executor executor;
    
  	private final boolean autoCommit;
  	private boolean dirty;
  	private List<Cursor<?>> cursorList;
    
  	public DefaultSqlSession(Configuration configuration, Executor executor, boolean autoCommit) {
    	this.configuration = configuration;
    	this.executor = executor;
    	this.dirty = false;
    	this.autoCommit = autoCommit;
  	}
    
  	public DefaultSqlSession(Configuration configuration, Executor executor) {
    	this(configuration, executor, false);
  	}
    
    // ......
}

以及BaseExecutor源码,如下:

/**
 * BaseExecutor实例与其transaction属性就是组合关系的实现
 */
public abstract class BaseExecutor implements Executor {

    private static final Log log = LogFactory.getLog(BaseExecutor.class);
	
    protected Transaction transaction;
  	protected Executor wrapper;
	
  	protected ConcurrentLinkedQueue<DeferredLoad> deferredLoads;
  	protected PerpetualCache localCache;
  	protected PerpetualCache localOutputParameterCache;
  	protected Configuration configuration;
	
  	protected int queryStack;
  	private boolean closed;

  	protected BaseExecutor(Configuration configuration, Transaction transaction) {
    	this.transaction = transaction;
    	this.deferredLoads = new ConcurrentLinkedQueue<>();
    	this.localCache = new PerpetualCache("LocalCache");
    	this.localOutputParameterCache = new PerpetualCache("LocalOutputParameterCache");
    	this.closed = false;
    	this.configuration = configuration;
    	this.wrapper = this;
  	}
    
    // ......
}

从这几个类中,发现了一个共同的特性:除了实现了定义行为的接口,然后与其他类的关系都是通过组合关系或者聚合关系来实现的,这就是合成复用原则的实现;

上一篇:ThinkPHP5中使用Workerman框架


下一篇:剑指offer 单词长度的最大乘积Java--二进制状态压缩