Example:
If you have a method that makes an "animal" run in your mobile game, you can define a single
IAnimal
interface, and for every animal define its own run chinematics.
public interface IAnimal {
Run();
}
public Dog : IAnimal{
public void Run() {
//DOG RUN CHINEMATICS
}
}
public Elephant: IAnimal{
public void Run() {
//ELEPHANT RUN CHINEMATICS
}
}
So you hide concrete implementation behind the IAnimal
abstraction (its usually called contract for interfaces).
So during your physics engine run you can simply define one method:
public void RunAnimal(IAnimal animal) {
animal.Run();
}
and call it like:
RunAnimal(new Dog()); //WILL CALL DOG CONCRETE METHOD
RunAnimal(new Elephant()); //WILL CALL ELEPHANT CONCRETE METHOD
So for RunAnimal
method the concrete impementation detail of animal is hidden behind IAnimal
"wall".
EDIT
So the answer to the question "why is programming to an interface not simply using the interface construct?" is:
An interface
is and instrument which you can use to construct interface
or contract
based architecture. The same can be achieved simply by using abstract base class
, or simple base class
with virtual methods
. So "programming to interface": is programming by having in mind to hide a concrete implementation detail from the consumer code (as much as it possible), to ensure maximum maintanibility, flexibility and scallability of your program. Use interface
, abstract class
, base class
, whatever you want.