Bridge Pattern
Author: Deron Eriksson
Description: This Java tutorial describes the bridge pattern, a structural design pattern.
Tutorial created using:
Windows Vista || JDK 1.6.0_11 || Eclipse JEE Ganymede SR1 (Eclipse 3.4.1)
(Continued from page 1) Our implementor interface is the Engine interface, which declares the go() method. Engine.javapackage com.cakes; public interface Engine { public int go(); } A BigEngine implements Engine. BigEngine has 350 horsepower. It's go() method reports that it is running and returns the horsepower. BigEngine.javapackage com.cakes; public class BigEngine implements Engine { int horsepower; public BigEngine() { horsepower = 350; } @Override public int go() { System.out.println("The big engine is running"); return horsepower; } } SmallEngine is similar to BigEngine. It has only 100 horsepower. SmallEngine.javapackage com.cakes; public class SmallEngine implements Engine { int horsepower; public SmallEngine() { horsepower = 100; } @Override public int go() { System.out.println("The small engine is running"); return horsepower; } } The BridgeDemo class demonstrates our bridge pattern. We create a BigBus vehicle with a SmallEngine implementor. We call the vehicle's drive() method. Next, we change the implementor to a BigEngine and once again call drive(). After this, we create a SmallCar vehicle with a SmallEngine implementor. We call drive(). Next, we change the engine to a BigEngine and once again call drive(). BridgeDemo.javapackage com.cakes; public class BridgeDemo { public static void main(String[] args) { Vehicle vehicle = new BigBus(new SmallEngine()); vehicle.drive(); vehicle.setEngine(new BigEngine()); vehicle.drive(); vehicle = new SmallCar(new SmallEngine()); vehicle.drive(); vehicle.setEngine(new BigEngine()); vehicle.drive(); } } The console output from the execution of BridgeDemo is shown here. Console OutputThe big bus is driving The small engine is running The vehicle is going at a slow speed. The big bus is driving The big engine is running The vehicle is going at a slow speed. The small car is driving The small engine is running The vehicle is going an average speed. The small car is driving The big engine is running The vehicle is going at a fast speed. Notice that we were able to change the implementor (engine) dynamically for each vehicle. These changes did not affect the client code in BridgeDemo. In addition, since BigBus and SmallCar were both subclasses of the Vehicle abstraction, we were even able to point the vehicle reference to a BigBus object and a SmallCar object and call the same drive() method for both types of vehicles. Related Tutorials:
|