Observe變種,校驗鏈

近期,由於項目需要,需要重新設計一套系統的攔截機制,其場景如下:

1.首先,系統需要對發起的請求做是否需要攔截過過濾,如果不需要攔截,則放過,進行第二層攔截

2.對於系統的角色的所屬權限進行校驗,如果爲角色默認權限則放過,如果非角色默認可使用權限,則交由第三層用戶權限進行控制。

3.當用戶權限進行改訪問的權限控制


以上,如果任意一層不通過,則不在由下一層進行校驗。


項目需要配合spring進行控制。


最後選定使用observer進行設計,採用observer變種模式進行鏈路校驗。


類設計圖:




系統提供一個統一的做驗證接口:IAuthenticateValidator,所作的內容就是向外界提供驗證接口,外界所能取得的內容爲內部驗證是否成功。其實現類AuthenticateValidator集成Observable接口,其作用爲,1.將各個Observer對象整合,2.一次調用各個Observer對象。

接下來就是調用中斷了,如果其中某個校驗器驗證失敗了,拋出業務異常,這時,校驗鏈就會中斷,但是一定需要注意,在AuthenticateValidator中需要對業務異常進行捕捉。


由於JDK util包中,默認的實現了observer和obserable接口,使得改模式的應用更多的被轉移至業務場景的貼閤中,而不是對改模式的自身實現。


核心代碼如下:


/**
*定義執行接口
*/
public interface IAuthenticateValidator {
	public void execute();
}

對方法的註冊及鏈狀調用

public class AuthenticateValidator extends Observable implements
		IAuthenticateValidator {

	public AuthenticateValidator() {
		this.addObserver(new DefaultAuthenticateValidator());
		this.addObserver(new RoleAuthenticateValidator());
		this.addObserver(new UserAuthenticateValidator());
	}

	public void execute() {
		setChanged();
		notifyObservers();
	}

}

核心的Observable調用器
synchronized (this) {
	    /* We don't want the Observer doing callbacks into
	     * arbitrary code while holding its own Monitor.
	     * The code where we extract each Observable from 
	     * the Vector and store the state of the Observer
	     * needs synchronization, but notifying observers
	     * does not (should not).  The worst result of any 
	     * potential race-condition here is that:
	     * 1) a newly-added Observer will miss a
	     *   notification in progress
	     * 2) a recently unregistered Observer will be
	     *   wrongly notified when it doesn't care
	     */
	    if (!changed)
                return;
            arrLocal = obs.toArray();
            clearChanged();
        }

        for (int i = arrLocal.length-1; i>=0; i--)
            ((Observer)arrLocal[i]).update(this, arg);


改設計還可以由其它模式實現,改實例只是說明Observer模式的一個變種。






發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章