mardi 31 juillet 2018

Is this Singleton + Lazy Loading?

public class UserSession
{
   private UserSession()
   {
   }

   public static UserSession Current
   {
       get
       {
           var session= (UserSession)HttpContext.Current.Session["_userSession"];
           if (session == null)
           {
               session = new UserSession();
               HttpContext.Current.Session["_userSession"] = session;
           }
           return session;
       }
   }

   public User User { get; set; }
}

//USAGE
UserSession.Current.User

I'm trying to figure out what patterns are used in this code. My understanding is that this is a

  1. Singleton Pattern (in fact there is a private constructor) and a
  2. Lazy Loading (or lazy initialization?) because the way the GET is implemented.

I'm also confused by the

  1. UserSession property which is the same type of the class and the usage itself seems weird to me.

Can someone explain what is happening here?

Aucun commentaire:

Enregistrer un commentaire