Resource sharing scenario using the Singleton design pattern in Java:

Category : Design Patterns | Sub Category : Questions on Design Patterns | By Prasad Bonam Last updated: 2023-07-12 07:34:29 Viewed : 79

Resource sharing scenario using the Singleton design pattern in Java:

Here is an example of implementing a resource sharing scenario using the Singleton design pattern in Java:

public class ResourceManager { private static ResourceManager instance; private int resourceCount; private ResourceManager() { // Initialize the resource(s) resourceCount = 0; } public static synchronized ResourceManager getInstance() { if (instance == null) { instance = new ResourceManager(); } return instance; } public void incrementResourceCount() { resourceCount++; } public void decrementResourceCount() { if (resourceCount > 0) { resourceCount--; } } public int getResourceCount() { return resourceCount; } }

In this example, the ResourceManager class is implemented as a Singleton using a private constructor and a static getInstance() method.

The ResourceManager class manages a shared resource (represented by the resourceCount variable in this example). The incrementResourceCount() method is used to increment the count of available resources, while the decrementResourceCount() method is used to decrement the count. The getResourceCount() method returns the current count of available resources.

To use the ResourceManager class, you can retrieve the singleton instance using ResourceManager.getInstance() and then perform resource-related operations:

ResourceManager resourceManager = ResourceManager.getInstance(); resourceManager.incrementResourceCount(); int count = resourceManager.getResourceCount(); resourceManager.decrementResourceCount();

In a multi-threaded environment, you might need to consider thread safety and synchronization depending on the nature of the resource sharing scenario.

Please note that this is a simplified example to illustrate the Singleton pattern and resource sharing. In real-world scenarios, resource sharing can involve more complex logic and considerations based on the specific requirements of the application and the resources being shared.

Related Articles

Leave a Comment: