桥接模式
桥接模式是将抽象部分与他的实现部分分离,使它们都可以独立的变化。
作用:
一个类中存在两个独立变化的维度,且这两个维度都需要进行扩展。
优点:
使用灵活,扩展性强。

1.创建一个品牌接口
public interface Brand {
void info();
}
2.两个品牌实现类
public class Apple implements Brand {
@Override
public void info() {
System.out.print("苹果");
}
}
public class Lenovo implements Brand {
@Override
public void info() {
System.out.print("联想");
}
}
3.创建一个抽象的产品类
public abstract class Computer {
protected Brand brand;
public Computer(Brand brand) {
this.brand = brand;
}
void name(){
brand.info();
};
}
4.两个产品实现类
public class Laptop extends Computer {
public Laptop(Brand brand) {
super(brand);
}
@Override
void name() {
super.name();
System.out.println("笔记本");
}
}
public class Desktop extends Computer {
public Desktop(Brand brand) {
super(brand);
}
@Override
void name() {
super.name();
System.out.println("台式机");
}
}
5.客户端使用
public class Client {
public static void main(String[] args) {
Computer apple = new Desktop(new Apple());
apple.name();
Computer lenovo = new Laptop(new Lenovo());
lenovo.name();
}
}


本文介绍了桥接模式在软件设计中的作用,它通过将抽象部分与实现部分分离,使得两者可以独立扩展。示例展示了如何创建一个品牌接口及其实现类,然后定义抽象的产品类和具体产品实现类,最后在客户端使用中展示了桥接模式的灵活性。桥接模式的主要优点是提高了代码的可扩展性和模块间的解耦。
726





