Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

"Program to an interface". What does it mean? [duplicate]

Tags:

java

oop

Possible Duplicate:
What does it mean to “program to an interface”?

I keep coming across this term:

Program to an interface.

What exactly does it mean? A real life design scenario would be highly appreciated.

like image 614
gameover Avatar asked Jan 02 '10 18:01

gameover


1 Answers

To put it simply, instead of writing your classes in a way that says

I depend on this specific class to do my work

you write it in a way that says

I depend on any class that does this stuff to do my work.

The first example represents a class that depends on a specific concrete implementation to do its work. Inherently, that's not very flexible.

The second example represents a class written to an interface. It doesn't care what concrete object you use, it just cares that it implements certain behavior. This makes the class much more flexible, as it can be provided with any number of concrete implementations to do its work.

As an example, a particular class may need to perform some logging. If you write the class to depend on a TextFileLogger, the class is forever forced to write out its log records to a text file. If you want to change the behavior of the logging, you must change the class itself. The class is tightly coupled with its logger.

If, however, you write the class to depend on an ILogger interface, and then provide the class with a TextFileLogger, you will have accomplished the same thing, but with the added benefit of being much more flexible. You are able to provide any other type of ILogger at will, without changing the class itself. The class and its logger are now loosely coupled, and your class is much more flexible.

like image 130
Eric King Avatar answered Oct 05 '22 12:10

Eric King