GofPatterns Gofpatterns





Structural Patterns  «Prev 

Bridge Pattern Code in Java

Bridge Pattern Description

The Java code below displays the pattern in action using the remote control example from Head First Design Patterns.
First, we have our TV implementation interface:

package com.java.structural.bridge;
//Implementor 
public interface TV{
	public void on();
	public void off(); 
	public void tuneChannel(int channel);
}

And then we create two specific implementations - one for Sony and one for Philips:
package com.java.structural.bridge;
//Concrete Implementor 
public class Sony implements TV{
  public void on(){
    //Sony specific on
	}
  public void off(){
    //Sony specific off
  }
  public void tuneChannel(int channel){
    //Sony specific tuneChannel
  }
}


package com.java.structural.bridge;
//Concrete Implementor 
public class Philips implements TV{
  public void on(){
    //Philips specific on
	}
  public void off()	{
    //Philips specific off
  }
  public void tuneChannel(int channel){
    //Philips specific tuneChannel
	}
}

These classes deal with the specific implementations of the TV from each vendor.
Now, we create a remote control abstraction to control the TV:

package com.java.structural.bridge;
//Abstraction
public abstract class RemoteControl{
  private TV implementor; 
  public void on(){
    implementor.on();
  }
  public void off(){
    implementor.off();
  }
  public void setChannel(int channel){
    implementor.tuneChannel(channel);
  }
}


As the remote control holds a reference to the TV, it can delegate the methods through to the interface.
But what if we want a more specific remote control, one that has the
+ / - 
buttons for moving through the channels? All we need to do is extend our RemoteControl abstraction to contain these concepts:

package com.java.structural.bridge;
//Refined abstraction
public class ConcreteRemote extends RemoteControl{
  private int currentChannel; 
  public void nextChannel(){
    currentChannel++;
    setChannel(currentChannel);
  }
  public void prevChannel(){
    currentChannel--;
    setChannel(currentChannel);
  }  
}

Disadvantage of the Bridge Pattern

One of the major disadvantages of this pattern is that, because it provides flexibility, the complexity is increased.
There is also possible performance issues with the indirection of messages.
The abstraction needs to pass messages along to the implementator for the operation to get executed.