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