Created
July 27, 2009 14:57
-
-
Save davidpadbury/156439 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
void Main() | |
{ | |
Person pete = new PersonFactory().GetPerson(1); | |
Console.WriteLine(pete.Name); | |
} | |
public class Person | |
{ | |
public virtual int Id { get; protected set; } | |
public virtual string Name { get; set; } | |
} | |
public class LazyPerson : Person | |
{ | |
private readonly PersonFactory loader; | |
private bool loaded; | |
private Person person; | |
public LazyPerson(int id, PersonFactory loader) | |
{ | |
Id = id; | |
this.loader = loader; | |
} | |
public override string Name | |
{ | |
get { EnsureLoaded(); return person.Name; } | |
set { EnsureLoaded(); person.Name = value; } | |
} | |
private void EnsureLoaded() | |
{ | |
if (loaded) return; | |
person = loader.LoadPerson(Id); | |
loaded = true; | |
} | |
} | |
public class PersonFactory | |
{ | |
public Person GetPerson(int id) | |
{ | |
return new LazyPerson(id, this); | |
} | |
public Person LoadPerson(int id) | |
{ | |
return new Person { Name = "Pete Smith" }; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment