Fabio_M
Fabio_M

Reputation: 879

Why Spring and Struts MVC implement singleton pattern for their controller classes?

Since the singleton pattern is for stateful objects and the servlet request/response in MVC are normally managed by a stateless object (the controller class) why they use singleton pattern only?

Upvotes: 0

Views: 674

Answers (1)

riccardo.cardin
riccardo.cardin

Reputation: 8353

Singleton pattern, as described in the GoF book Design Patterns, is intended to be applied to stateless object. Having only one instance of a Singleton in the application, all its clients share the same instance and then the same state. In most of the cases, this is not the behaviour a object should have. But, it is not a Singleton feature to be stateless or stateful. It's your design that has to decide if a Singleton should or not have a state.

Speaking about Spring and Struts Controllers, imho it is correct that they are modelled as Singleton. These object should have not a state, and if they have some attributes, they usually are services class, that are Singleton too.

Finally, Controllers' building process has a cost. So it is also for performance reasons that they are implemented as Singleton classes.

Upvotes: 2

Related Questions