Understanding singleton and multiple instances

1. What is a single instance with multiple instances;
2. How to generate a single instance with multiple instances;
3. Why use a single instance with multiple instances
4. When to use a single instance and when to use multiple instances;


1. What is a singleton and multiple instances:
  The so-called singleton means that all requests are handled by one object. For example, the objects of our commonly used service and dao layers are usually singletons, while multiple instances refer to each request using a single instance. New objects to process, such as action; 
2. How to generate singleton and multiple instances:
     In general SSH, singleton is the default in spring. If multiple instances are to be generated, add scope=" to the bean of the configuration file. prototype"; 
3. Why use a single instance with multiple instances:
      The reason for using a single instance is that there is no need to create a new object for each request, which wastes both CPU and memory;
     the reason for using multiple instances is to prevent concurrency problems ; That is, a request changes the state of the object, and the object processes another request at this time, and the change of the state of the object by the previous request causes the object to process another request incorrectly;
     there is only one standard for singleton and multiple instances : When the object contains a state that can be changed (more precisely , the state will change in practical applications), there are multiple instances, otherwise a single instance; 4. When to use a single instance? When to use multiple instances?     For struts2, action must use multiple instances, because the action itself contains the value of the request parameter, which can be changed;   for STRUTS1, the action can be singleton, because the value of the request parameter is placed in the actionForm, and Not in action; in    addition, it does not mean that service or dao must be a singleton. The standard is the same as that mentioned in point 3. I have seen that some services also contain changeable states, and the execution method is also Relying on this state, but using the same singleton, there will be hidden bugs, and concurrent bugs are usually difficult to reproduce and find;
     



Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325382036&siteId=291194637