15 April 2011

Design Pattern and Princples in nanonutshell: Program to an interface, not an implementation

Principle :
"Program to an interface, not in implementation"
What does mean ?
It means that you should tie your  dependencies (named as well: relationships) glue ( tie) with  interfaces not with classes.
It makes code much easier to maintain ,modify (switch to other implementation) and extend , because  you will change less code make easier to switch from one implementation to another.

How it looks in practice ?

Look on example which contain 3 elements
1) Interface Train

package programtoaninterfacenotanimplementation;

/**
*
* @author dsymonowicz
*/
public interface Train {
String name();
String speed();
}



2)Class Express Train

package programtoaninterfacenotanimplementation;

/**
*
* @author Dominik Symonowicz
*/
public class ExpressTrain implements Train {

public String name() {
return "Express train";
}

public String speed() {
return "ridiculous";
}

}



3)  Example Player

package programtoaninterfacenotanimplementation;



/**
*
* @author dsymonowicz
*/
public class Main {

/**
* @param args the command line arguments
*/
public static void main(String[] args) {
Train train = new ExpressTrain();
System.out.println(train.name());
System.out.println(train.speed());
}

}


 When you run program you will see on screen(Example from netbeans):

run:
Express train
ridiculous
BUILD SUCCESSFUL (total time: 0 seconds)

 
Sources:
 http://danielroop.com/blog/2008/06/28/program-to-an-interface-not-an-interface/ 
http://www.artima.com/lejava/articles/designprinciples.html 
http://www.javaranch.com/

No comments:

Post a Comment