NOTE

Design Patterns I Have Used

A short interview-style note on where singleton, prototype, factory, builder, facade, decorator, template method, state, strategy, and proxy patterns were used.

Software Architecture & Engineering2 min readhistorical

This is a historical learning note and may contain outdated or incomplete understanding.

1. Creational

1.1. Singleton Pattern

Explain it? A class has one and only one instance.

Can you implement a singleton by hand? Singleton Pattern.md When have you used it? During Netty startup.

1.2. Prototype Pattern

Creating an object may require a lot of data preparation; it can be easier to clone an existing object as the prototype and then modify its value.

Implementation? Implement the Cloneable interface and override clone.

When have you used it? When a notification system needed to return both unread-count data and message content to the front end, a shallow copy was used.

1.3. Simple Factory

Separate class creation from class use.

Implementation? A map.

When have you used it? Use it together with singleton, state, or strategy patterns, returning different implementations for different actions, such as notifications, tickets, object storage, or search.

1.4. Builder Pattern

Used to construct an object composed of many smaller objects when the construction process is complex, such as various builders.

Implementation? Similar to @Data.

When have you used it? UrlBuilder, ExcelBuilder, and HTMLParser.

2. Structural

2.1. Facade Pattern

Encapsulate a complex process in one class, such as utility classes.

Implementation?

When have you used it? ZooKeeper utility classes.

2.2. Decorator Pattern

Add new functionality to a class without changing the original code.

When have you used it? Separate parameter validation from the actual logic.

3. Behavioral

3.1. Template Method

Suitable when the overall steps of an algorithm are fixed but some parts vary; abstract the varying parts.

Implementation? An abstract class defines a method that calls abstract methods, and subclasses implement those abstract methods.

When have you used it? For Elasticsearch searches, such as adding highlighting.

3.2. State Pattern

An object has multiple statuses, and each status has different actions.

Implementation? Use it with a factory method, defining an abstract class and abstract methods.

When have you used it? Notification-system keepalive, for example.

3.3. Strategy Pattern

Choose different algorithms by type to achieve the same goal.

Implementation? Same as above.

When have you used it? Choose different object-storage implementations for file upload/download.

3.4. Dynamic Proxy

Add new functionality to a class without changing the original code.

When have you used it? Use Spring AOP for authorization checks.

Discussion

Sign in with GitHub to comment. Discussions are stored as GitHub Issues.View on GitHub