简体   繁体   中英

How to return a constant value, not creating a new object every time

I have a function used to populate data into map

public final class ConfigurationService {
   public final RMap populateCache(RedissonClient client) {
      RMap map = client.getMap("Config");
      map.put("key1", "value1");
      map.put("key2", "value2"):
      return map;
   }
}

and I call that function in my main class, how can I make it return a constant value, not creating a new object every time

does change the function populateCache() return a map works?

ConfigurationService configurationService = new ConfigurationService()
configurationService.populateCache(client)

I am not sure whether I understood your intention. Anyway, to answer your question, I notice that your method doesn't need to instantiate any new object or using ConfigurationService instance members at all, thus you can just declare your method as static:

public final static RMap populateCache(RedissonClient client) {
...
}

So, when you have to invoke the method, there's no need to create a new ConfigurationService object, but you just do this way:

RMap map = ConfigurationService.populateCache(client);

I think that works fine for your specific case, as the populateCache looks just an utility method, so it's ok to declare it as static and make it manipulate an object that you pass in input.

ConfigurationService.populateCache(client);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM