#687 – An Example of Containment
October 8, 2012 Leave a comment
One common strategy is to use inheritance when modeling an is-a type of relationship (e.g. a Terrier is-a Dog) and to use containment when modeling a has-a type of relationship (e.g. a Family has-a Dog).
Here’s an example of containment, where a Dog object contains instances of the DogName and DogAbilities classes.
internal class DogName { public DogName(string humanName, string nameInDogWorld) { HumanName = humanName; NameInDogWorld = nameInDogWorld; } public string HumanName { get; set; } public string NameInDogWorld { get; set; } } internal class DogAbilities { public DogAbilities(List<string> knownTricks, bool canBark) { KnownTricks = knownTricks; CanBark = canBark; } public List<string> KnownTricks { get; set; } public bool CanBark { get; set; } } public class Dog { public Dog(string humanName, string firstTrick, bool canBark) { Name = new DogName(humanName, GenerateSecretDogWorldName()); List<string> abilities = new List<string>(); abilities.Add(firstTrick); Abilities = new DogAbilities(abilities, canBark); } public void Bark() { if (Abilities.CanBark) Console.WriteLine("Woof!"); else Console.WriteLine("Wag"); } public void DoTrick(string trick) { if (Abilities.KnownTricks.Contains(trick)) Console.WriteLine("Doing {0} trick", trick); } public void TeachTrick(string newTrick) { if (!Abilities.KnownTricks.Contains(newTrick)) Abilities.KnownTricks.Add(newTrick); } private DogName Name { get; set; } private DogAbilities Abilities { get; set; } private string GenerateSecretDogWorldName() { return "His noble woofiness sir poops-a-lot"; } }