Spring中涉及的設(shè)計模式總結(jié)
點擊上方藍色字體,選擇“標星公眾號”
優(yōu)質(zhì)文章,第一時間送達
1.簡單工廠(非23種設(shè)計模式中的一種)
2.工廠方法
3.單例模式
public Object getSingleton(String beanName){
//參數(shù)true設(shè)置標識允許早期依賴
return getSingleton(beanName,true);
}
protected Object getSingleton(String beanName, boolean allowEarlyReference) {
//檢查緩存中是否存在實例
Object singletonObject = this.singletonObjects.get(beanName);
if (singletonObject == null && isSingletonCurrentlyInCreation(beanName)) {
//如果為空,則鎖定全局變量并進行處理。
synchronized (this.singletonObjects) {
//如果此bean正在加載,則不處理
singletonObject = this.earlySingletonObjects.get(beanName);
if (singletonObject == null && allowEarlyReference) {
//當某些方法需要提前初始化的時候則會調(diào)用addSingleFactory 方法將對應(yīng)的ObjectFactory初始化策略存儲在singletonFactories
ObjectFactory<?> singletonFactory = this.singletonFactories.get(beanName);
if (singletonFactory != null) {
//調(diào)用預(yù)先設(shè)定的getObject方法
singletonObject = singletonFactory.getObject();
//記錄在緩存中,earlysingletonObjects和singletonFactories互斥
this.earlySingletonObjects.put(beanName, singletonObject);
this.singletonFactories.remove(beanName);
}
}
}
}
return (singletonObject != NULL_OBJECT ? singletonObject : null);
}
4. 適配器模式
5.裝飾器模式
6.代理模式
7.觀察者模式
8.策略模式
9.模版方法模式
public interface StatementCallback{
Object doWithStatement(Statement stmt);
} public class JdbcTemplate {
public final Object execute(StatementCallback callback){
Connection con=null;
Statement stmt=null;
try{
con=getConnection();
stmt=con.createStatement();
Object retValue=callback.doWithStatement(stmt);
return retValue;
}catch(SQLException e){
...
}finally{
closeStatement(stmt);
releaseConnection(con);
}
}
...//其它方法定義
}
Jdbc使用方法如下:
JdbcTemplate jdbcTemplate=...;
final String sql=...;
StatementCallback callback=new StatementCallback(){
public Object=doWithStatement(Statement stmt){
return ...;
}
}
jdbcTemplate.execute(callback);
作者:iCoding91
來源:csdn.net/caoxiaohong1005/article/details/80039656

評論
圖片
表情


