Skip to content

Instantly share code, notes, and snippets.

@sunmeat
Created November 24, 2023 13:38
Show Gist options
  • Save sunmeat/4f28d7a86befe6aed7dac4a3b05385e7 to your computer and use it in GitHub Desktop.
Save sunmeat/4f28d7a86befe6aed7dac4a3b05385e7 to your computer and use it in GitHub Desktop.
composition example C#
class PegLeg // деревянная нога
{
public string Color { get; set; } // brown will be OK
public bool Dirty { get; set; } // yes / no
public double Length { get; set; } // inches
public int Usability { get; set; } // 0 - 100%
public PegLeg()
{
Console.WriteLine("Peg Leg C-TOR!");
}
//~PegLeg() // в С++ проще отследить момент уничтожения объекта-контента (части), там есть деструкторы.
//{ // в С# у нас финализаторы, поэтому надеяться на их явный вызов без реализации IDisposable не приходится
// Console.WriteLine("Peg Leg DESTRUCTOR!");
//}
}
class HandHook // рука-крючок
{
public string Material { get; set; }
public int Usability { get; set; }
public bool Dirty { get; set; }
public bool CanMakeSelfy { get; set; }
public HandHook()
{
Console.WriteLine("Hand Hook C-TOR!");
}
}
class EyePatch // наглазник
{
public string Color { get; set; } // black is timeless classic
public double Size { get; set; } // XXL
public bool Elastic { get; set; } // yes / no
public bool Leather { get; set; } // yes / no
public EyePatch()
{
Console.WriteLine("Eye Patch C-TOR!");
}
}
class Pirate
{
public string Nickname { get; set; }
public PegLeg Leg { get; set; }
public HandHook Hand { get; set; }
public EyePatch Patch { get; set; }
public Pirate(string nickname)
{
Nickname = nickname;
Leg = new PegLeg();
Hand = new HandHook();
Patch = new EyePatch();
Console.WriteLine("Pirate C-TOR!");
}
public void CaptureShip()
{
Console.WriteLine($"{Nickname} says: Prepare a boarding party!!!");
}
public void SingSong()
{
Console.WriteLine($"{Nickname} singing: \"...Yo-ho-ho, and a bottle of rum!!!\"");
}
}
class Program
{
static void Main()
{
var p = new Pirate("Captain Jack Sparrow");
p.CaptureShip();
p.SingSong();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment