To put it simply without interfaces all behaviour is concretely defined in the class. With interfaces the behaviour is defined in the interface. Why is that important? Because as the last user just said it decouples your design from your implementation.
It's one of those things that just kind of "clicks" after a while.
Take this example (I steal the scenario from a design tutorial at JavaRanch):
PHP Code:
class StandardEngine {
function start()
function stop()
function injectFuel()
}
class Car {
private $engine;
public function __construct() {
$this->engine = new StandardEngine();
}
// ... snip ....
}
$car = new Car();
Ok, so you got yourself a car to sell and it's got the standard engine. Great, it drives.
Now you want a car with a FastEngine instead. How do you do it?
Modify the class? Nope.
Injecting the dependency (a car *needs* an engine) is a better way to go:
PHP Code:
interface Engine {
function start()
function stop()
function injectFuel()
}
class StandardEngine implements Engine {
}
class FastEngine implements Engine {
}
Now your interface tells you what methods an Engine provides in its public API so you know you can *guarantee* any class implementing the Engine interface will provide those methods.
PHP Code:
class Car {
private $engine;
public function __construct(Engine $engine) {
$this->engine = $engine;
}
// ... snip ...
}
//Our orignal design equivalent
$car = new Car(new StandardEngine());
//Our fatser car. Same behaviour, different underlying implementation
$car = new Car(new FastEngine());
You could do the same thing without interfaces but using interfaces just adds a level of reassurance that your injected object really does what you think it does
Bookmarks