I am not quite clear as to why or when to use Interfaces. Can someone post a complete, simple and small example of an Interface using VB.NET in a Console Application. How is it extensible?
相关问题
- Carriage Return (ASCII chr 13) is missing from tex
- How to store image outside of the website's ro
- What uses more memory in c++? An 2 ints or 2 funct
- 'System.Threading.ThreadAbortException' in
- how to use special characters like '<'
In short: Favor Composition over Inheritance
Interfaces are simply a common set of member definitions that you want one or more classes to support. The key is that you have to provide the functionality explicitly when you implement an interface.
You can achieve similar results using inheritance since two sub-classes can inherit fully-functional members from the base. But the downside of inheritance is that your sub-classes end up having a hard dependency on the base class.
Consider the following classes:
You could say that these two classes are somewhat related because they both have an OpenDoor() method. You might be tempted to even create a base class to extract common functionality.
You could then use this abstraction like this:
However, relating a house to a car based solely on the fact that you can access them with a key is a pretty weak abstraction. Heck, even a can of beans can be openable!
But there are other points where relation might occur as well. For example, both a car and a house might have air conditioning:
Should TurnOnAirConditioning() be extracted to the base class too? What does it have to do with being an OpenableProperty? Could a JewelrySafe class inherit from OpenableProperty without an AC? The better answer in this situation is to extract Interfaces and use these to compose the functionality in our classes rather than inherit:
Then your abstractions can be consumed as such:
The SecurityService could then be used to inspect the Car, House, and JewelrySafe, while the ThermostatService could be used only to test the AC of the Car and House.
Which should produce the following results:
Consider this simple interface:
Without even writing any more code, I can start dealing with this concept in other parts of my code. For instance:
And voila -- now for any class I write, if I just make it implement
IWeightedValue
then I can calculate the weighted average for a collection of instances of this class.