Skip to content

Instantly share code, notes, and snippets.

@Porges
Created November 16, 2015 23:41
Show Gist options
  • Save Porges/23b8a8a950fa163d0f46 to your computer and use it in GitHub Desktop.
Save Porges/23b8a8a950fa163d0f46 to your computer and use it in GitHub Desktop.
using System;
namespace Foob
{
interface IEater
{
void Eat();
bool CanEat { get; }
}
class Eater : IEater
{
void IEater.Eat() => Eat();
bool IEater.CanEat => CanEat();
// Or take via constructor to prevent runtime boogeymen
public Action Eat { get; set; } = () => { throw new NotImplementedException(); };
public Func<bool> CanEat { get; set; } = () => { throw new NotImplementedException(); };
}
interface IWoofer
{
void Woof();
}
class Woofer : IWoofer
{
void IWoofer.Woof() => Woof();
// Or take via constructor to prevent runtime boogeymen
public Action Woof { get; set; } = () => { throw new NotImplementedException(); };
}
interface IMeower
{
void Meow();
}
class Meower : IMeower
{
void IMeower.Meow() => Meow();
// Or take via constructor to prevent runtime boogeymen
public Action Meow { get; set; } = () => { throw new NotImplementedException(); };
}
// Dog is a woofer and an eater:
class Dog : IWoofer, IEater
{
private readonly IWoofer _woofer;
private readonly IEater _eater;
public Dog(IWoofer woofer, IEater eater)
{
_woofer = woofer;
_eater = eater;
}
// Delegate everything:
public void Woof() => _woofer.Woof();
public void Eat() => _eater.Eat();
public bool CanEat => _eater.CanEat;
}
class Program
{
static void Main(string[] args)
{
var timesEaten = 0;
var dog = new Dog(
new Woofer
{
Woof = () =>
{
Console.WriteLine("woof!");
},
},
new Eater
{
Eat = () =>
{
Console.WriteLine($"I've eaten {++timesEaten} times");
},
CanEat = () => timesEaten < 3,
});
dog.Eat();
dog.Eat();
dog.Woof();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment