Design Mode: bridge mode; design mode: Bridge
Bridge, as the name suggests, builds a bridge between two objects that have a relationship. The two objects can be independent of each other, reducing coupling and solving the strong dependency between inheritance.
For example, there are many electronic products, such as mobile phones and tablets, and many manufacturers, such as Apple and Xiaomi. If multi-inheritance is used, classes increase by product, and classes in the bridging mode increase by sum. Obviously, the number of classes can be reduced.
The Bridge Mode decouples abstraction and implementation so that they can change independently. Here there are two concepts: Abstraction and implementation, not to mention implementation. The preceding example shows that an electronic product is an abstract product, while a manufacturer implements it accordingly.
The code is provided below, which is relatively simple to write. Draw a UML diagram by yourself:
-----------------------------------------------------------
//ElectronicProduct.javapackage org.uestc.bridge;public abstract class ElectronicProduct {Manufacturer manufacturer;public ElectronicProduct(Manufacturer manufacturer) {this.manufacturer = manufacturer;}public void GetBrand() {this.manufacturer.GetBrand();//System.out.println(")}}class Phone extends ElectronicProduct {public Phone(Manufacturer manufacturer) {super(manufacturer);}public void GetBrand() {manufacturer.GetBrand();System.out.println("phone");}}class Pad extends ElectronicProduct {public Pad(Manufacturer manufacturer) {super(manufacturer);}public void GetBrand() {manufacturer.GetBrand();System.out.println("pad");}}
//Manufacture.javapackage org.uestc.bridge;public interface Manufacturer {void GetBrand();}class Apple implements Manufacturer {@Overridepublic void GetBrand() {System.out.print("Apple's ");}}class XiaoMi implements Manufacturer {@Overridepublic void GetBrand() {// TODO Auto-generated method stubSystem.out.print("xiaomi's ");}}
//client.javapackage org.uestc.bridge;public class Client {public static void main(String[] args) {ElectronicProduct iphone = new Phone(new Apple());iphone.GetBrand();ElectronicProduct xiaoMiPad = new Pad(new XiaoMi());xiaoMiPad.GetBrand();}}
The running result is as follows:
Apple's phonexiaomi's pad