15.01.2013 Views

Free-ebooks-library - Bahar Ali Khan

Free-ebooks-library - Bahar Ali Khan

Free-ebooks-library - Bahar Ali Khan

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

public class Animal<br />

{<br />

public string Name;<br />

public int Popularity;<br />

public Animal (string name, int popularity)<br />

{<br />

Name = name; Popularity = popularity;<br />

}<br />

}<br />

public class AnimalCollection : Collection <br />

{<br />

// AnimalCollection is already a fully functioning list of animals.<br />

// No extra code is required.<br />

}<br />

public class Zoo // The class that will expose AnimalCollection.<br />

{ // This would typically have additional members.<br />

public readonly AnimalCollection Animals = new AnimalCollection();<br />

}<br />

class Program<br />

{<br />

static void Main()<br />

{<br />

Zoo zoo = new Zoo();<br />

zoo.Animals.Add (new Animal ("Kangaroo", 10));<br />

zoo.Animals.Add (new Animal ("Mr Sea Lion", 20));<br />

foreach (Animal a in zoo.Animals) Console.WriteLine (a.Name);<br />

}<br />

}<br />

As it stands, AnimalCollection is no more functional than a simple List; its<br />

role is to provide a base for future extension. To illustrate, we’ll now add a Zoo<br />

property to Animal, so it can reference the Zoo in which it lives and override each of<br />

the virtual methods in Collection to maintain that property automatically:<br />

public class Animal<br />

{<br />

public string Name;<br />

public int Popularity;<br />

public Zoo Zoo { get; internal set; }<br />

public Animal(string name, int popularity)<br />

{<br />

Name = name; Popularity = popularity;<br />

}<br />

}<br />

public class AnimalCollection : Collection <br />

{<br />

Zoo zoo;<br />

public AnimalCollection (Zoo zoo) { this.zoo = zoo; }<br />

Customizable Collections and Proxies | 299<br />

Collections

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!