次の方法で共有


Scott’s lazy loader

Scott Wisniewski posted a lazy loader implementation on his blog.  He coded it blind, without the help of a compiler that could do C# generics.  I went back through and made it legal C# code.  I also did a little refactoring.

 

  • The ILazyLoader is now nested in the LazyLoad<T> class, which means it doesn’t need its own type parameter.
  • The getter has only one return.
  • A DefaultLoad derives from LazyLoad, and adds the ‘new()’ constraint to T.

 

The code is now legal C#, but I haven’t verified that it actually works yet.

public class LazyLoad<T>

{

      public interface ILazyLoader

      {

            T CalculateValue();

      }

      private T value_;

      private bool didFetch_ = false;

      private ILazyLoader lazyLoader_;

      public LazyLoad(ILazyLoader lazyLoader)

      {

            lazyLoader_ = lazyLoader;

      }

      public T Value

      {

            get

            {

                  if (!didFetch_)

                  {

                        didFetch_ = true;

                        value_ = lazyLoader_.CalculateValue();

                  }

                  return value_;

            }

      }

}

public class DefaultLazyLoad<T> : LazyLoad<T>

            where T : new()

{

      public class DefaultConstructLazyLoader : ILazyLoader

      {

            public DefaultConstructLazyLoader() { }

            public T CalculateValue()

            {

                  return new T();

            }

      }

      public DefaultLazyLoad() : base(new DefaultConstructLazyLoader()) { }

}

Comments

  • Anonymous
    April 30, 2004
    Thanks for fixing my code :)
  • Anonymous
    April 30, 2004
    Cool idea. Note that the getter is not thread-safe (but this is easily fixed)
  • Anonymous
    May 05, 2004
    Nice.
    An interface (ILazyLoader) with just one method, maybe you want to use a delegate there...

    I've been thinking about the same problem applied to the Singleton pattern. Can Generics be used to implement it once and for all? Any thoughts?
  • Anonymous
    May 05, 2004
    About the Singleton: it's easy to have the generic Singleton be a seperate class. It would look like: Singleton<MyClass>.GetInstance().MyMethod() or Singleton<MyClass>.Instance.MyMethod() if you use a property.

    But often you see the class and the singleton merged, so that you ensure MyClass can't be instanciated outside of the singleton.
    Plus if you change your mind and decide you want 3 pooled instances instead of 1 (a "Threepleton"?) you need to change code all over the place.

    I'm not sure if/how you can do in C#+generics.
  • Anonymous
    May 05, 2004
    singleton: In C++, I wrote a singleton mixin. It was nice & simple, and did wonders for clarity. I'm disappointed that mixins in C# are so clunky. I hope that a future C# language change would let mixins into C# programs.