Middle+
What design patterns are common in JavaScript and TypeScript that are not found in Java?
sobes.tech AI
Answer from AI
- Singleton (easier to implement in JS/TS using modules and closures).
- Module (an implicit language pattern).
- Prototype (through prototype inheritance).
- Mixin (via Object.assign, classes, or factory functions).
- Revealing Module Pattern (using closures).
- Factory Function (an alternative to class constructors).
- Dependency Injection (often through factories or containers, not as tightly coupled to annotations as in Java).
Examples of differences:
- Singleton:
// singleton.js
const instance = {
data: 'some data'
};
export default instance; // Simple export of a single instance
In Java, a static method getInstance() and a private constructor are needed.
- Module:
// module.js
const privateVar = 'private';
export function publicMethod() {
console.log(privateVar);
}
In Java, explicit class and access modifier declarations are required.
- Prototype:
const animal = {
speak() {
console.log('...');
}
};
const dog = Object.create(animal);
dog.speak = function() {
console.log('woof');
};
dog.speak(); // woof
In Java, inheritance is based on classes.
- Mixin:
const searchable = {
search() {
console.log('Searching...');
}
};
class Article {
constructor(title) {
this.title = title;
}
}
Object.assign(Article.prototype, searchable);
const myArticle = new Article('Hello');
myArticle.search(); // Searching...
Java does not have native support for mixins (interfaces or composition are used instead).