Member-only story

Deep Analysis of Java Design Patterns: Utilizing the Sharing Element Pattern to Achieve Efficient Object Sharing and Memory Optimization

1、 Introduction

Beck Moulton
2 min readJan 8, 2025

The core idea of the Xiangyuan model is “sharing”. When a large number of similar objects need to be created in the system, the Xiangyuan pattern optimizes the creation and use of objects through the following steps:

  1. Extract shared status :Firstly, identify the shareable states in the object and encapsulate them in a shared element class.
  2. Separate the state of change :Separate states that cannot be shared or change with context from the shared element class as external states.
  3. Create Xiangyuan Factory :Implement a shared element factory to manage the creation and caching of shared element objects. When a client requests a new token, the factory first checks if the same type of token already exists in the cache. If it exists, return the instance; Otherwise, create a new instance of Xiangyuan and add it to the cache.
  4. Client usage :The client code obtains the Xiangyuan object through the Xiangyuan Factory and sets its external state as needed. When performing operations, the Xiangyuan object will combine its internal state with the external state passed in to complete the task.

5、 The use of Xiangyuan mode

**** :

  1. Reduce memory consumption By sharing object instances…

--

--

Beck Moulton
Beck Moulton

Written by Beck Moulton

Focus on the back-end field, do actual combat technology sharing Buy me a Coffee if You Appreciate My Hard Work https://www.buymeacoffee.com/BeckMoulton

No responses yet