Design Patterns – Why Use Interfaces in C#?

cdesign-patternsinterfaces

OK. I am learning design patterns. Every time I see someone code an example of a design pattern they use interfaces. Here is an example:

http://visualstudiomagazine.com/Articles/2013/06/18/the-facade-pattern-in-net.aspx?Page=1

Can someone explain to me why was the interfaces needed in this example to demonstrate the facade pattern? The program work if you pass in the classes to the facade instead of the interface. If I don't have interfaces does that mean

Best Answer

Interfaces are unrelated to Design Patterns. They are about Object-Orientation. In OO, the type of an object is defined by its behavior, i.e. by the protocol it speaks (its methods).

Classes in languages like Java and C#, however, also define representation (fields) in addition to behavior (methods). One of the basic tenets of OO is that objects cannot know the representation of other objects even of the same type. However, if you use classes as types, other objects of the same class can know the representation of other objects, even private fields. Therefore, using classes as types breaks OO. (Unfortunately, in both Java and C#, classes are types.)

The only way to do object-oriented programming in Java or C# is to use classes only as factories (i.e. only directly after new) and never as types (i.e. never as the type of a field, return type or parameter type of a method or type argument to a generic type, never cast to a class, never use it with instanceof). And as types, use only interfaces, not classes (and certainly not primitives in Java).

That's what interfaces do: they enable object-oriented programming in Java and C#, without them, OOP would simply be impossible in those languages.

Related Topic