Skip to content

Instantly share code, notes, and snippets.

@xray
Last active June 7, 2019 16:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save xray/9ce2ceab4fca2ef847360c8c441d0c7a to your computer and use it in GitHub Desktop.
Save xray/9ce2ceab4fca2ef847360c8c441d0c7a to your computer and use it in GitHub Desktop.
An example of composition in C#
using System;
public interface IMovement
{
void Fly();
}
public class AerialMovement : IMovement
{
public static void Fly()
{
Console.WriteLine("Zoooooommm!");
}
}
public class Airplane
{
private readonly IMovement _movement;
public Airplane(IMovement movement)
{
_movement = movement;
}
public static void Fly()
{
return _movement.Fly();
}
}
public class Canary
{
private readonly IMovement _movement;
public Canary(IMovement movement)
{
_movement = movement;
}
public static void Fly()
{
return _movement.Fly();
}
public static void Sing()
{
Console.WriteLine("Tweet tweet!");
}
}
var aerialMovement = new AerialMovment();
var 737 = new Airplane(aerialMovement);
var tweety = new Canary(aerialMovement);
737.Fly();
tweety.Fly();
tweety.Sing();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment