Saturday, October 8, 2016

Programming to an Interface

Case Study 2

The display module of a computer should be flexible, so we can change it easily, or we can change it dynamically (at runtime). We can say the display module is like a strategy, and a client can change the strategy at any time. Technically, the display is a function or contract, but it can have multiple implementations, so it's better to create this contract as an interface, and every implementation will provide its own display mechanism so at runtime, the Computer can call it.
So our Java solution looks like the following:



interface displayModule
{
public void display();
}
public class Monitor implements displayModule
{
  public void display()
  {
   System.out.println(“Display through Monitor”);
  }
}
public class Projector implements displayModule
{
  public void display()
  {
   System.out.println(“Display through projector”);
  }
}
public class Computer
{
 displayModule dm;// programming through interface as variable part
public void setDisplayModule(displayModule dm)
{
this.dm=dm;
}
public void display()
{
dm.display();
}
public static void main(String args[])
{
Computer cm =new Computer();
displayModule dm = new Monitor();
displayModule dm1 = new Projector();
cm. setDisplayModule(dm);
cm. display();
cm. setDisplayModule(dm1);
cm. display();
}
}
Output:
  Display through Monitor
  Display through projector







No comments:

Post a Comment

Using Zotero for academic writing