The bridge pattern is a design pattern used in software engineering which is meant to "decouple an abstraction from its implementation so that the two can vary independently" [1]. The bridge uses encapsulation, aggregation, and can use inheritance to separate responsibilities into different classes.
In basic, in the abstract class, keep the stuf you will never override and in concrete stuff add non-commmon implementations in concrete section
In below example, each of abstactions method can be overridden by refined/concrete abstraction. The implementor references the Abstration and hold function that would be common for that abstraction. The concrete implementation add on extra functinality.
public abstract class TV {
public void On() {}
public void Off() {}
public void tuneChannel(int channel) {}
}
public class Sony extends TV {
public void On() {
//Sony way of off
}
public void Off() {
//Sony way of ON
}
public void tuneChannel(int channel) {
System.out.println("Channel switched to : " + channel);
//Sony way of setting channel
}
}
public abstract class RemoteControl {
private TV tv;
RemoteControl(TV args) {
tv = args;
}
public void on() {
tv.On();
}
public void off() {
tv.Off();
}
public void setChannel(int channel) {
tv.tuneChannel(channel);
}
}
public class SonyRemote extends RemoteControl {
int channelNo = 0;
public SonyRemote(TV tv) {
super(tv);
}
public void nextChannel() {
channelNo++;
setChannel(channelNo);
}
}
public class Client {
public static void main(String [] args) {
Sony sony = new Sony();
SonyRemote remote = new SonyRemote(sony);
remote.nextChannel();
remote.nextChannel();
remote.nextChannel();
}
}
References:
No comments:
Post a Comment