Caching mechanism using the Singleton design pattern in Java

Category : Design Patterns | Sub Category : Questions on Design Patterns | By Prasad Bonam Last updated: 2023-07-12 01:51:55 Viewed : 346


Caching mechanism using the Singleton design pattern in Java:

Here is an example of implementing a caching mechanism using the Singleton design pattern in Java:

java
public class Cache { private static Cache instance; private Map<String, Object> cacheData; private Cache() { cacheData = new HashMap<>(); } public static synchronized Cache getInstance() { if (instance == null) { instance = new Cache(); } return instance; } public void put(String key, Object value) { cacheData.put(key, value); } public Object get(String key) { return cacheData.get(key); } public void remove(String key) { cacheData.remove(key); } public void clear() { cacheData.clear(); } }

In this example, the Cache class is implemented as a Singleton using a private constructor and a static getInstance() method. The getInstance() method ensures that only one instance of the Cache class is created.

The Cache class maintains a Map (cacheData) to store key-value pairs for caching purposes. The put() method is used to add an entry to the cache, the get() method retrieves the value associated with a given key, the remove() method removes a key-value pair from the cache, and the clear() method clears the entire cache.

To use the Cache class, you can retrieve the singleton instance using Cache.getInstance() and then perform cache operations such as put(), get(), remove(), and clear().

java
Cache cache = Cache.getInstance(); cache.put("key1", "value1"); Object value = cache.get("key1"); cache.remove("key1"); cache.clear();

Note that this is a basic example to illustrate the Singleton pattern and caching mechanism. In real-world scenarios, you might need to handle thread safety, cache expiration, and other advanced features based on your specific requirements.


Search
Related Articles

Leave a Comment: