views:

86

answers:

3

Hi,

I have the following, very interesting class...

pubilc class Thing{

public Thing()
{
 DoSomethingThatTakesALongTime();
}

pubic boolean CheckSomething(string criteria)
{
 return  criteria == "something";
} }

In my ASP.Net MVC application, I need to call make a call to CheckSomething, very frequently.

As you can see, the constructor takes a long time to load.

What approaches can I use to cache the class? Keep in mind that I want to keep it testable....and I don't know what that entails!!!!

Cheers,

ETFairfax

+2  A: 

You can create a static instance of that class.

Somewhere:

public static Thing singleThing = new Thing ();

Now upon the first access of the singleThing variable for a given application domain your constructor will work out. After this is done the object will be kept in memory until the end of the application domain (server restart, update of code, changes in web.config, recycling etc.). It means the once initialized object will be available to all clients of your application.

Developer Art
+1 for simplicity
kurast
A: 

if your thing class does something global to your aplication (not session dependant) just make the class static or add the instance to the cache (HttpContext.Cache)

Drevak
+2  A: 

You could use the Factory Pattern to create it (Flyweight pattern to share memory)

Create a Factory that returns an instance of the class. The factory would look like this

if instance in cache

  • return cached instance

if not

  • create instance
  • cache instance
  • return instance

For cache you could use HttpContext Cache or Enterprise Library Cache.

EDIT

Interesting discussion below of which pattern this is.

My understanding is as follows:

  • I ask something to create the object, that something is a factory, therefore factory pattern.
  • I try to reuse an object in memory, flyweight pattern. The python code in this example looks very much like my answer: http://en.wikipedia.org/wiki/Flyweight%5Fpattern
  • But there is only a single instance of the object, therefore the singleton pattern
  • The cache where the object is stored is also a singleton
Shiraz Bhaiji
+1 but I'd say that's the flyweight pattern. Not that much different from factory though.
JulianR
@JulianR, Thanks I have updated based on you comment.
Shiraz Bhaiji
Wouldn't that be a Singleton and not a Flyweight?
Dean J