Design Patterns Whiteboard Image.png

I. Proxy - Structural Pattern

The Proxy is a familiar Design Pattern for developers, used to represent an original resource. The Proxy provides functionalities similar to the original resource but with high customizability.

The Proxy acts as a substitute for the original resource, hiding complex details or adding necessary features such as access control, caching, or load balancing.

II. Real-world Example

The system frequently needs to query user information from a main database. However, directly querying the main database can increase latency and reduce system performance. Therefore, we use a Proxy that acts as a cache to temporarily store frequently queried data.

The Proxy checks the cache, and if the data exists in the cache, it returns it immediately. Otherwise, it queries the main database and updates the cache.

This use case introduces the mechanism of a Proxy for searching users (User) between the MainDB (main database) and the Stack (cache) to improve performance.

  1. Definition of User:

    A User only has an ID attribute (int), representing a user entity.

  2. Shared Interface:

    The UserFinder interface defines the Find(ID int) method to search for a user by their ID. Both MainDB and Stack adhere to this interface.

  3. Main Database (MainDB):

    The main database where users are stored. UsersDB provides the Find function to search for a user and the Add function to add a new user.

  4. Proxy (UserFinderProxy):

    The Proxy is a middle layer that uses the Stack (cache memory) for faster access before searching in the MainDB.

The class diagram for the above scenario would be depicted as follows:

hL912i8m4Bpd5NjirVO1GQJM8lGW2Ef9F8GcGh6sagHWKVzkazJGI4KFvfJTdSpCxYOIad1PdmkKbvBn8yaOx0JZoxoaZCCDGNl6e48lJQ05-U0fm0GOvnNtqGEXh212w6VTWm3I12kmMnL9R04wnh0_gCjt5GEOK-hLIaRLV0oZZlLDPYD9Th9AElgFagPonSoWrhowDbPnHV8oYV6hPzT7ZyZa5-H2ibmsPc2_-zjMciMn.png

III. Implementation