Chuyển đến nội dung

Bài 39 · Architectural and Modern Patterns

Patterns Across Languages: Java, C++, Python and JavaScript

See how design patterns change across Java, C++, Python and JavaScript: which ones vanish with closures, duck typing and modules, and what RAII replaces.

The classic patterns were described in the 1990s using C++ and Smalltalk. Java copied the style almost word for word. Since then, languages have gained first-class functions, modules, generators and richer standard libraries, and several patterns shrank to a line of code or disappeared. A pattern is a solution to a problem in a particular language's context. When the language solves the problem for you, the ceremony is not needed.

This lesson walks through which patterns change shape in Java, C++, Python and JavaScript, shows the same idea in two languages side by side, and ends with advice on how to avoid writing "Java in Python".

What changes between languages

First-class functions Strategy, Command and Observer shrink to a function.
Duck typing No interface needed to be substitutable.
Modules A module is already a single shared instance.
1 / 2

Patterns that shrink: functions as values

In Java before version 8 you needed an interface and a class to pass behavior around. Today Java has lambdas, but its type system still expects a functional interface. JavaScript and Python let you pass a function directly.

Read-only Java, the old way:

Java
interface DiscountStrategy {
    double apply(double price);
}

class HalfPrice implements DiscountStrategy {
    public double apply(double price) { return price * 0.5; }
}

double total = checkout(100.0, new HalfPrice());
// With a lambda: checkout(100.0, price -> price * 0.5);

The same Strategy and Command ideas in JavaScript and Python are just values. Compare them side by side. First JavaScript:

JS Strategy, Command and Observer as plain functions (JavaScript)

Press Run (or Ctrl + Enter) to see the console output here.

No output.

And the same ideas in Python:

Python Strategy, Command and Observer as plain functions (Python)

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The classes in the textbook versions are still the right tool when the behavior has state, several methods, or a name that benefits from documentation. Without those, a function is clearer. See Strategy, Command and Observer for the full forms.

Duck typing replaces many interfaces

In Java and C++, substituting one class for another requires a declared relationship: an interface or a base class. In Python and JavaScript, anything with the right methods works ("if it walks like a duck..."). This removes the need for explicit interfaces in patterns such as Adapter (often a small wrapper, or even a function), Strategy, and Decorator.

The trade-off is that mistakes appear later. Static languages catch a missing method at compile time; dynamic ones catch it when that line runs. Both ecosystems have added tools to get the benefits back: Python's typing.Protocol and type hints, TypeScript's interfaces for JavaScript.

Read-only Python showing a structural interface with no inheritance:

Python
from typing import Protocol

class Notifier(Protocol):
    def send(self, to: str, text: str) -> None: ...

class EmailNotifier:                     # no "implements" anywhere
    def send(self, to: str, text: str) -> None:
        print("mail", to, text)

def alert(notifier: Notifier) -> None:   # accepts anything with a matching send()
    notifier.send("ops", "disk is full")

Singleton: modules and static initialization

A Singleton in Java or C++ needs a private constructor, a static instance and care with threads. In JavaScript and Python, a module is loaded once and cached, so a module-level object is already a single shared instance:

JS Modules as singletons, and the cost of shared state

Press Run (or Ctrl + Enter) to see the console output here.

No output.

The disadvantages of Singleton (hidden dependencies, hard testing) apply equally to a module-level global, so the advice to inject dependencies still holds. In Java, the simplest safe singleton today is an enum with one constant or a dependency-injection container's "singleton" scope. In C++ a function-local static variable is initialized thread-safely since C++11.

C++ and RAII: cleanup without a pattern

C++ has deterministic destruction. RAII (Resource Acquisition Is Initialization) ties a resource to an object's lifetime: the constructor acquires it, the destructor releases it, even when an exception is thrown. It replaces patterns that other languages need, such as try/finally blocks and parts of the Template Method used for "open, work, close" skeletons. Smart pointers (std::unique_ptr, std::shared_ptr) and lock guards (std::lock_guard) are RAII.

Read-only C++:

C++
#include <mutex>
#include <memory>

std::mutex m;
int counter = 0;

void increment() {
    std::lock_guard<std::mutex> lock(m);   // locks here
    ++counter;
}                                          // unlocks here, even on exceptions

auto widget = std::make_unique<Widget>(); // freed automatically at scope end

Other languages have their own version of the same guarantee: Java's try-with-resources, Python's with statement and context managers, JavaScript's using declarations (in newer runtimes) and try/finally. Python shows the idea compactly:

Python Context managers: Python's answer to RAII

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The lock is released in both cases. In C++ you get this with destructors, in Java with try (var r = ...), and in Python with with.

Iterator, Visitor and Factory in practice

  • Iterator. Java has Iterable and Iterator; C++ has iterator categories and ranges; Python has __iter__/__next__ and generators; JavaScript has the iteration protocol and function*. In all four the pattern is built into for loops. You rarely write one by hand except through a generator.
  • Visitor. Java and C++ need double dispatch with accept/visit methods. Python can use functools.singledispatch, and JavaScript commonly uses a switch on a type tag. C++17's std::visit with std::variant and Java 21's pattern-matching switch over sealed types have made the pattern lighter in those languages as well.
  • Builder. Java needs a builder class because it lacks named arguments. Python has keyword arguments and dataclasses, JavaScript uses an options object, and C++ often uses designated initializers (C++20) or fluent setters.
  • Factory Method. In Python and JavaScript classes are values, so a factory can be a dictionary of constructors. In Java and C++ you typically write a creator hierarchy or a static factory method.
  • Prototype. JavaScript has prototypes built into its object model, and structuredClone makes copies. Python has copy.copy and copy.deepcopy. C++ uses copy constructors, and Java uses copy constructors or clone() carefully.

Here is a factory plus builder in both dynamic languages, side by side, to show how little ceremony they need:

JS Factory and options object (JavaScript)

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Python Factory and keyword arguments (Python)

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Avoiding "Java in Python"

A well-known trap is translating textbook diagrams literally: a SingletonMeta metaclass where a module would do, a StrategyInterface with one implementation, getters and setters for every field. Ask these questions before writing a pattern:

  1. Does the language already solve this? (closures, generators, context managers, modules, enum, pattern matching)
  2. Is there a real second implementation, or only a hypothetical one? Follow the rule of three from Beyond SOLID.
  3. Would a plain function or data structure be clearer?

Keep the vocabulary even when the class disappears. Saying "this callback is a strategy" or "that wrapper is a decorator" still gives your team a shared shorthand.

Check your understanding

Quick check · 5 questions

of 5 answered You scored / 5 · perfect!

  1. 1. Why do Strategy and Command often shrink to a plain function in JavaScript and Python?

    When functions are values, you can pass behavior directly instead of wrapping it in an interface and a class.
  2. 2. What does RAII do in C++?

    The constructor acquires the resource and the destructor releases it, so cleanup is automatic and exception-safe.
  3. 3. Which is the closest Python equivalent of a scoped RAII guard?

    enter and exit run at the beginning and end of the with block, even if an exception is raised.
  4. 4. Why is a module-level object in Python or JavaScript often enough instead of a classic Singleton class?

    Because the module is loaded once, its top-level objects are shared. Shared mutable state still has the usual testing drawbacks.
  5. 5. What is the risk of duck typing compared with declared interfaces?

    Static languages report a missing method at compile time. Dynamic languages need tests, type hints or protocols to get the same safety.

Summary

  • Patterns are solutions in the context of a language; stronger languages need less ceremony.
  • Closures and first-class functions turn Strategy, Command and Observer into plain functions when no extra state is needed.
  • Duck typing removes many interface declarations; protocols and type hints add static checking back.
  • Modules are already single shared instances; the testing caveats of Singleton still apply.
  • RAII (C++), try-with-resources (Java), with (Python) and try/finally or using (JavaScript) guarantee cleanup.
  • Keep the shared vocabulary of patterns, but avoid translating textbook diagrams literally.

Next lesson: Anti-Patterns and Code Smells.

Theo dõi tiến độ của bạn

Tạo tài khoản miễn phí để đánh dấu bài đã học và tiếp tục từ chỗ bạn dừng lại trên mọi thiết bị.