Implement the properties encapsulation design pattern

In need of a method to control document activation logic, where activating a document involves adding it to a list of activeDocuments and setting a flag to true. Direct access to the isActive property should be prohibited.

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

To address this issue, one possible solution is creating two interfaces: DocumentServiceInterface with a setActive() method and DocumentInterface without it. This setup prevents |DocumentComponent from activating the document while allowing the service to do so.

Are there any design patterns or strategies that can provide a solution?

Iterating through a list of documents to determine their active status is not feasible due to the complexity of the application structure and the potential for thousands of documents.

Answer №1

One possible solution for this problem is to utilize the Mediator Design Pattern. Alternatively, if you prefer to hide the method from client code, you can consider using es2015 symbol methods. By doing so, the code outside of your DocumentService and DocumentModel classes will not be able to access the active method since the visibility of ACTIVE is limited to the module. Here's an example implementation:

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

Answer №2

One possible approach with javascript could be:

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

However, I personally find this method unconventional and difficult to comprehend.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the reason for and <br> not functioning in a string?

I am encountering an issue when attempting to print the content of an object. Some of the properties within the object contain tags, making it challenging to create new elements in JavaScript without knowing which properties will include these tags. How ...

Priority is given to strings over numbers

Here's some code I'm working with: <tbody> <tr> <td class="float-left"> <!-- {{selectedTemplat?.modifiedAt | da ...

Issue with reading the current length of an array object in a while loop in Angular 6

After successfully splitting an array into parts, I decided to add some filters to only include the items in the list that have an action status of (4). However, I encountered a problem where the while loop couldn't read the length of the array. This ...

Undefined will be returned if the data in AngularJS is not set within the $scope

I have developed a factory that contains a list of functions which are called when the state changes. On page load, I am calling dtoResource.rc1Step1DTO(). Although the function executes, when I check the result in the console, it returns undefined. Below ...

Disabling dates in Kendo Date Time Picker (Angular): An easy guide

<input id="startDate" kendo-date-time-picker k-ng-model="vm.startDate" k-on-change="vm.updateStartDate()" required /> Can someone please explain how to incorporate disabled dates into this date picker without utilizi ...

The Angular TypeScript service encounters an undefined issue

Here is an example of my Angular TypeScript Interceptor: export module httpMock_interceptor { export class Interceptor { static $inject: string[] = ['$q']; constructor(public $q: ng.IQService) {} public request(config: any) ...

Dynamically assign values to object properties of varying data types using indexing

My goal is to dynamically update one object using another object of the same type. This object contains properties of different types: type TypeOne = 'good' | 'okay'; type TypeTwo = 'default' | 'one'; interface Opt ...

Using Angular route resolve to handle the sessionStorage login status

I have successfully created a login system using Angular JS. Once the user logs in, a session storage variable is set and they are redirected to a dashboard page (which should only be accessible when logged in). $window.sessionStorage["isLoggedIn"] = true ...

Resolving the Conflict Between Jquery and require.js

Exploring the concept of jQuery no conflict, I referred to the explanation provided in this article Using private jquery with RequireJS - issue after optimisation However, upon loading my page with additional configurations like the ones below: ...

The dynamic duo of AngularJS and Kendo UI

Hey there! I'm currently working with Angular JS and Kendo UI in my application, but I've run into a peculiar error that's got me stumped. The error reads: TypeError: object is not a function TypeError: Function expected at Anonymous functi ...

Troubleshooting: Issue with Angular 2 FormArray

Hey there! I'm currently working on my Angular 2 Recipe app where I want to display multiple ingredient details. I am using a FormArray but encountered an error while debugging with the browser developer tools. The error displayed on the Console tab i ...

Unique Angular Directive Utilizing Alternate Template

My directive, named myDirective, has a variable called type. When I use <my-directive type="X">, I want the directive to utilize templateUrl: x-template.html. On the other hand, when I use <my-directive type="Y">, I want it to use templateUrl: ...

What is the process for importing a function dynamically in a Next.js TypeScript environment?

Currently, I am utilizing a React modal library known as react-st-modal, and I am attempting to bring in a hook named useDialog. Unfortunately, my code is not functioning as expected and appears like this: const Dialog = dynamic<Function>( import(& ...

ng-pattern is not throwing any errors

After spending hours on this issue, I realized it was time to seek help here. I have been struggling with setting up an input field that displays a specific message when someone tries to type in a number. My extensive research brought me to ng-pattern as ...

Is it possible to manipulate an Angular #variableName in order to retrieve an ElementRef for an HTML element?

Suppose I have a scenario where I create a button like this: <button #myButton>My Button</button> ...and then use ViewChild in the following way: @ViewChild('myButton', { static: true }) createButton: ElementRef; In this case, creat ...

Is there a method for executing ng-serve alongside expressjs?

I am currently following an Angular6/Express tutorial. In the tutorial, they utilize the following scripts: "scripts": { "ng": "ng", "start": "ng build && node ./bin/www", "build": "ng build", "test": "ng test", "lint": "ng lint", "e2e ...

Retrieving form data from within the resource error callback scope

For my client-side validation on submit, I am calling a resource if the form is valid. On success, everything works fine. However, when encountering an error handler, I also perform server-side validation on my data transfer object bean which contains Hibe ...

Change the input field font style in AngularJS

Check out this Plunker link for validation of input field: http://plnkr.co/edit/iFnjcq?p=preview The validation only allows numbers to be entered and automatically adds commas. My query is, if a negative number is entered in the field, how can I change th ...

Presenting SQL information in a hierarchical Angular grid for easy visualization

As a newcomer to Angular, I have a requirement to display data in a multilevel/hierarchical Angular Grid. The data is retrieved from a SQL Database using a query with arguments provided in the where clause. Some questions that come to mind are: Is there ...

Assistance required with NODEJS [DB] architecture for Multi-tenant system using [mysql]

I am developing a SaaS application using NestJS with Knex and Objection.js (MySQL). Here are some possible solutions I'm considering: Utilizing a single database with tenantId differentiation Creating a schema per tenant Having a dedicated database ...