Sobes.tech
Middle+

What patterns are common in Java that are not found in JavaScript and TypeScript?

sobes.tech AI

Answer from AI

Factory Method, Abstract Factory, Builder, Singleton, Prototype, Adapter, Decorator, Facade, Flyweight, Proxy, Command, Iterator, Mediator, Memento, Observer (although in JS there is EventEmitter/RxJS, the pattern "out of the box" is less common in its classic form), State, Strategy, Template Method.

In JavaScript/TypeScript, many of these patterns are solved with other means:

  • Prototype inheritance instead of classical inheritance.
  • Higher-order functions and closures.
  • Dynamic typing (for JS).
  • Modular system.

For example:

  • Singleton: In JS/TS, often implemented via modules or closures, not static class methods.
    // Singleton implementation via module
    const singletonInstance = {
      data: 'some data'
    };
    
    module.exports = singletonInstance;
    
  • Factory Method / Abstract Factory: In JS/TS, functions returning objects or simple classes are often used. There is no strict need for interfaces and abstract classes in the same sense as in Java.
    // Simple "factory" in JS
    function createObject(type) {
      if (type === 'A') {
        return { name: 'Object A' };
      } else if (type === 'B') {
        return { name: 'Object B' };
      }
      return null;
    }
    
  • Decorator: In JS/TS, these are either wrapper functions or decorator syntax (experimental or standardized in TS).
    // Example decorator in TypeScript
    function logMethod(target: any, propertyKey: string, descriptor: PropertyDescriptor) {
      const originalMethod = descriptor.value;
    
      descriptor.value = function(...args: any[]) {
        console.log(`Calling ${propertyKey} with args: ${JSON.stringify(args)}`);
        const result = originalMethod.apply(this, args);
        console.log(`Method ${propertyKey} returned: ${JSON.stringify(result)}`);
        return result;
      };
    
      return descriptor;
    }
    
    class MyClass {
      @logMethod
      myMethod(arg1: string): string {
        return `Processed: ${arg1}`;
      }
    }
    
  • Builder: Often implemented via method chaining or simple object literals.
    // Builder example with method chaining
    class Config {
      constructor() {
        this._settings = {};
      }
    
      withSetting(key, value) {
        this._settings[key] = value;
        return this; // Return this for chaining
      }
    
      build() {
        return this._settings;
      }
    }
    
    const myConfig = new Config()
      .withSetting('timeout', 1000)
      .withSetting('retry', 3)
      .build();
    

Patterns GOF, developed in the context of OOP languages like Java, can be less idiomatic or overly complex for JavaScript/TypeScript, where functional or prototype-oriented approaches are often preferred.

What patterns are common in Java that are not found… - sobes.tech