2017-03-29 118 views
0

我想封裝如何激活文檔(布爾)的邏輯。當文檔被激活時,它應該被添加到activeDocuments列表中,並且該標誌應該被設置爲true。我想禁止直接訪問isActive屬性。封裝屬性設計模式

class DocumentService { 
     private activeDocuments : Map<DocumentModel> = new Map<DocumentModel>(); 

     // Activates the document and adds it to the list 
     activateDocument(document: DocumentModel) { 
       document.setActive(); 
       activeDocuments.set(document.id, document); 
     } 
} 


class DocumentModel { 
     private isActive: boolean; 

     setActive() { 
       this.isActive = true; 
     }   
} 

class DocumentComponent { 
     documentSelected() { 
      // this.document.setActive() - SHOULD BE FORBIDDEN because the document is not added to the activedocument list ! 
      this.documentService.activateDocument(this.document); 
     } 
} 

,我想通了這個問題的唯一解決方案是創建一個具有SETACTIVE()方法,沒有它兩個接口DocumentServiceInterface和DocumentInterface所以它可防止| DocumentComponent激活文件,但服務仍然可以激活文檔。

有沒有可以解決這個問題的設計模式/配方?

通過的文件列表進行遍歷,以檢查它是否是活躍與否是不是一種選擇,因爲結構是在應用程序更爲複雜,文件的數量應該擴展(例如可能有多個萬份文件)

回答

0

一個JavaScript具體辦法做到這將是這樣的:

setActive() { 
    if (arguments.callee.caller.toString()!=='DocumentService') 
     throw new Exception(); 
} 

但我覺得它很不尋常,難以閱讀

+0

打破界面隔離原則 – teter

2

可以使用Mediator Design Pattern來解決這個問題。或者如果只想將方法隱藏到客戶端代碼中,則可以使用es2015符號方法,那麼Doc​​umentService & DocumentModel中的代碼將無法訪問活動方法,因爲ACTIVE的可見性僅在模塊中可見,代碼如下:

const ACTIVE = Symbol("active"); 

class DocumentService { 
    private activeDocuments: Map<String,DocumentModel> = new Map<String,DocumentModel>(); 

    // Activates the document and adds it to the list 
    activateDocument(document: DocumentModel) { 
     document[ACTIVE](); 
     this.activeDocuments.set(document.id, document); 
    } 

} 

class DocumentModel { 
    public id: string; 
    private isActive: boolean; 

    [ACTIVE]() { 
     this.isActive = true; 
    } 
}