Open Source Your Knowledge, Become a Contributor
Technology knowledge has to be shared and made accessible for free. Join the movement.
Single Access Design Pattern - TypeScript demo
Table of Contents
- Table of Contents
- What is it?
- When to use it?
- Class Interface
- Example usage with tests
- Coding exercise
- Final implementation
What is it?
The Single Access design pattern restricts the access to a resource, allowing only a single retrieval. Consecutive accesses trigger an error, which usually points to a logical error in the code.
The design emerged in a project that uses a shared information object across multiple states. It provides a way to ensure that the shared data is being accessed only once in each state, and being updated at the end. This has helped point out logical errors where the object is being accessed multiple times, or not being set properly, within a state.
The pattern is used in the project like this:
- When a new state is entered, the necessary shared information is retrieved and stored in instance variables. The instance variables can be changed.
- Trying to retrieve the information from the shared object a second time triggers an access error.
- Not setting the shared information at the end of a state triggers an error in the next access.
As this design controls the ownership of an object, it is similar to C++11's
When to use it?
When you must guarantee that a resource:
- is only accessed once
- is updated by the object that accessed it
This is what an interface for the single access implementation looks like. The
<T> is a generics notation, that allows specifying to TypeScript what the actual object's type is, and also points out that this will work for any object. If you're not familiar with generics, have a look at the TypeScript's Generics documentation.
Example usage with tests
The following file contains some test cases, versus which your implementation will be tested (if you attempt it!). Test cases are a good way of showing off different use cases, while keeping it easy to follow.
This is an opportunity to have a go at implementing the design pattern. This will help you understand it better, so I definitely recommend giving it a go.
If you want some guidance for where to start, scroll further down.
If you want the final code, go to the end of the page.
- The resource needs to be stored
- The access to the resource needs to be tracked