Created
January 31, 2013 03:02
-
-
Save Porges/4679582 to your computer and use it in GitHub Desktop.
a pseudo-pattern for 'external' interfaces
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
/* Given: */ | |
// An interface | |
interface ICountable | |
{ | |
int Count { get; } | |
} | |
// A class that 'should' implement the interface | |
class Foo | |
{ | |
public int Count; | |
} | |
// A class that accepts the interface | |
class CountableAcceptor | |
{ | |
public int GetCount(ICountable count) | |
{ | |
return count.Count; | |
} | |
} | |
/* Make this work: */ | |
void Main() | |
{ | |
var acceptor = new CountableAcceptor(); | |
var foo = new Foo{ Count = 1 }; | |
// use our 'should' class as the parameter | |
acceptor.GetCount(foo); | |
} | |
/* By doing this: */ | |
static class CountableAcceptorExtensions | |
{ | |
public static int GetCount(this CountableAcceptor acceptor, CountableFooAdaptor foo) | |
{ | |
return acceptor.GetCount(foo); | |
} | |
} | |
class CountableFooAdaptor : ICountable | |
{ | |
private Foo _foo; | |
public CountableFooAdaptor(Foo foo) | |
{ | |
_foo = foo; | |
} | |
public static implicit operator CountableFooAdaptor(Foo foo) | |
{ | |
return new CountableFooAdaptor(foo); | |
} | |
public int Count { get { return _foo.Count; } } | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment