Bridge design pattern
Today we are going to learn a new design pattern, the bridge design pattern. Its focus is to separate implementation and abstraction into layers that do not affect each other and can be extended independently
Let’s look at the traditional way of doing things, instead of using Bridges, let the abstraction layer and the implementation layer establish a relationship.
The model of Xiaomi mobile phone is selected here. It can be seen that both the abstraction layer and the implementation layer are not independent of each other, and when one of them changes, the ones associated with it will change. It is for this reason that the bridge design pattern emerges.
Let’s look specifically at the characteristics of the bridge design pattern.
- The implementation class
- An abstract class
- The bridge
Let’s look at a UML diagram of the bridging design pattern
Its main characteristic is in the implementation layer and abstraction layer cut into a layer, this layer as a bridge, using the concrete implementation class, it can be passed in, the two separate from each other, independent. Easy to expand.
Based on the above schematic diagram, let’s improve the problem of xiaomi mobile phone models in the beginning.
We introduce a Model as a bridge between the implementation layer and the abstraction layer, and pass in the corresponding implementation class by constructing parameters to realize specific operations.
Let’s look at the actual code implementation.
- Behavior to achieve
interface Mi {
void play(a);
}
class Note extends Model{
public Note(Mi mi) { super(mi); } @Override void play(a) { super.mi.play(); System.out.println("This is the Note phone."); } } class Redme extends Model{ public Redme(Mi mi) { super(mi); } @Override void play(a) { super.mi.play(); System.out.println("This is a RedMe phone."); } } class Mix extends Model{ public Mix(Mi mi) { super(mi); } @Override void play(a) { super.mi.play(); System.out.println("This is the Mix."); } } Copy the code
- The bridge
abstract class Model{
protected Mi mi ;
public Model(Mi mi){
this.mi = mi ;
}
abstract void play(a) ; } Copy the code
- Concrete implementation class
class Note4 implements Mi{
@Override
public void play(a) {
System.out.println("It's Note4");
}
} class RedmePro20 implements Mi{ @Override public void play(a) { System.out.println("It's RedmePro20"); } } class Mix3 implements Mi{ @Override public void play(a) { System.out.println("It's Mix3"); } } Copy the code
Finally, the bridge design pattern is over. This is the sixth design pattern, but it should be obvious to you that design patterns complicate a problem, decouple the system, and make the scalability of the system more elegant. Program decoupling is achieved by introducing an intermediate layer, aggregating, and so on. At this time, we will also think of a very important problem, time for space, space for time, the same is the sacrifice of one side to achieve one side.
This article is formatted using MDNICE