The Bridge (Bridge) pattern is defined as follows: Separate abstraction and implementation so that they can change independently. It is implemented by using combination relationships instead of inheritance relationships, thereby reducing the coupling degree of the two variable dimensions of abstraction and implementation.
1. Separation of abstraction and implementation, strong scalability
2. Comply with the opening and closing principle
3. Comply with the principle of synthesis and reuse
4. Its implementation details are transparent to customers
Since the aggregation relationship is established at the abstraction layer, developers are required to design and program for abstraction to correctly identify the system There are two independently changing dimensions in the system, which increases the difficulty of understanding and designing the system.
You can separate the abstraction part from the implementation part, cancel the inheritance relationship between the two, and use the combination relationship instead.
Case: Blue Rabbit Palace Master buys a skirt
The skirt has two dimensions, namely color and style.
The colors are yellow and red;
The styles are divided into long skirts and short skirts;
Abstraction (Abstraction) role: Color
Extended abstraction ( Refined Abstraction) Role: Yellow and Red
Implementor Role: Style
Concrete Implementor Role: Long Skirt and Short Skirt
Color interface, declare a show() abstract method
public interface Color { void show(); }
yellow class and implement the color interface
public class ColorYellow implements Color { @Override public void show() { System.out.println("黄色的"); } }
red Class and implement the color interface
public class ColorRed implements Color { @Override public void show() { System.out.println("红色的"); } }
Skirt class, declare a color attribute and an abstract method
abstract class Qun { protected Color color; protected Qun() { } protected Qun(Color color) { this.color = color; } public abstract void shows(); }
Inherit the Skirt class, and Implement the abstract method
public class QunChang extends Qun { protected QunChang() { } protected QunChang(Color color) { super(color); } @Override public void shows() { System.out.println("长裙"); color.show(); } }
Inherit the skirt class and implement the abstract method
public class QunDuan extends Qun { protected QunDuan() { } protected QunDuan(Color color) { super(color); } @Override public void shows() { System.out.println("短裙"); color.show(); } }
new and pass a red object as a parameter to the long skirt .
public class Demo { public static void main(String[] args) { Color color = new ColorRed(); Qun qun = new QunChang(color); qun.shows(); } }
The above is the detailed content of How to implement the bridge mode of Java design pattern. For more information, please follow other related articles on the PHP Chinese website!