桥接模式:是将抽象部分与 实现部分分离,使他们可以队里变化,是一种对象结构型模式,又称为柄体模式或者接口模式
实战一下,将品牌和类型相互分离,当有需要的时候互相组合:
先写一个品牌的接口
package bridge;
//品牌
public interface Brand {
void info();
}
分别实现一个苹果品牌还有一个联想品牌:
package bridge;
//苹果品牌
public class Apple implements Brand {
@Override
public void info() {
System.out.print("苹果");
}
}
package bridge;
//联想品牌
public class Lenovo implements Brand {
@Override
public void info() {
System.out.print("联想");
}
}
然后类型写两个,分别是台式机和笔记本,然后写两个实现类:
package bridge;
//抽象的电脑类
public abstract class Computer {
//和品牌进行组合,桥
protected Brand brand;
public Computer(Brand brand) {
this.brand = brand;
}
public void info() {
//自带品牌
brand.info();
}
}
class DestTop extends Computer {
public DestTop(Brand brand) {
super(brand);
}
@Override
public void info() {
super.info();
System.out.println("台式机");
}
}
class LapTop extends Computer {
public LapTop(Brand brand) {
super(brand);
}
@Override
public void info() {
super.info();
System.out.println("笔记本");
}
}
最后测试一下,需要什么,就组合什么:
package bridge;
public class Test {
public static void main(String[] args) {
//苹果笔记本
Computer computer = new LapTop(new Apple());
computer.info();
//联想台式机
Computer computer1 = new DestTop(new Lenovo());
computer1.info();
}
}
好了,今天先到这里~