mercredi 29 mars 2017

Encapsulate the properties design pattern

I want to encapsulate the logic how a document is activated(boolean). When a document is activated it should be added to a list of activeDocuments and the flag should be set to true. I want to forbid the direct access to the isActive property.

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);
      }
}

The only solution that i figured out for this problem is to create two interfaces DocumentServiceInterface that has a setActive() method and DocumentInterface that doesn't have it so it prevents the |DocumentComponent to activate the document but the service can still activate the document.

Is there a design pattern/ recipe that can solve this ?

Aucun commentaire:

Enregistrer un commentaire