桥接模式简介

  • 桥接是用于把抽象化与实现化解耦,使得二者可以独立变化。这种类型的设计模式属于结构型模式,它通过提供抽象化和实现化之间的桥接结构,来实现二者的解耦。
  • 这种模式涉及到一个作为桥接的接口,使得实体类的功能独立于接口实现类。这两种类型的类可被结构化改变而互不影响。
品牌接口Brand
1
2
3
4
//产品品牌
public interface Brand {
void name();
}
实现类品牌A和品牌B
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
//A品牌
public class ABrand implements Brand {
@Override
public void name() {
System.out.print("A品牌");
}
}

//B品牌
public class BBrand implements Brand {
@Override
public void name() {
System.out.print("B品牌");
}
}
抽象产品类Product
1
2
3
4
5
6
7
8
9
10
11
12
13
//抽象产品类
public abstract class Product {
//带品牌,组合方式
private Brand brand;

public Product(Brand brand) {
this.brand = brand;
}

public void name() {
brand.name();//品牌名称
}
}
子类产品C和D
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
//C产品
public class CProduct extends Product {
public CProduct(Brand brand) {
super(brand);
}

@Override
public void name() {
super.name();
System.out.println("C产品");
}
}

//D产品
public class DProduct extends Product {
public DProduct(Brand brand) {
super(brand);
}

@Override
public void name() {
super.name();
System.out.println("D产品");
}
}
测试类
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
public class Test {
public static void main(String[] args) {
Brand brandA = new ABrand();//A品牌
Brand brandB = new BBrand();//B品牌
CProduct cProduct = new CProduct(brandA);//C产品,带A品牌,即A品牌的C产品
DProduct dProduct = new DProduct(brandB);//D产品,带B品牌,即B品牌的D产品
cProduct.name();
dProduct.name();
/**
* 输出结果:
* A品牌C产品
* B品牌D产品
*/
}
}
测试结果
1
2
A品牌C产品
B品牌D产品