Created
November 16, 2015 23:41
-
-
Save Porges/23b8a8a950fa163d0f46 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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