I have an application which stores many many variables as attributes on the session. Each time I need one, I have to remember what the attribute name was exactly, and cast it back to its type to use it.
I was considering using a single object to contain all these variables, and call it something like “SessionManager” so that I only need to remember one attribute name and casting will not fail.
I wondered if this was a pattern or if there is a similar or better existing pattern?
Sounds like you need some kind of cache for your session.
You can’t help but know the attribute name. However you could skip the casting part with a specialized method for each object type (ideally you wouldn’t have many diffrent types other than primitives)
Since you mention Java EE i’d go for a stateless bean that implements the following operations
defined in an interface:
In the bean implementation i would add for extra flexibility:
Define two classes that implement the former interface (besides the bean class). One could store and read the values from memory and the other could do so from the database. And add an strategy patter that lets you select the class you want to use (again since you use Java EE this could be an Application Server variable)
Summing it up:
Create an interface that exposes the types you need (to avoid casting)
Implement said interface in an EJB
Implement said interface in as many classes as different data stores you want to use
Implement a simple strategy pattern (no need for a dedicated class, an switch statement in the EJB would do) that selects the appropiate class.
Call the EJB client from your code.
Hope that helps