什么是桥接模式?
桥接模式是将抽象部分与他实现部分分离,使得他们都可以独立的变化,这是一种对象结构型模式,又称(interface)接口模式。
桥接模式的目的
通过组合的方式建立两个类之间的联系,而不是继承
桥接模式运用常景
一个类存在两个或多个独立变化的维度,而这两个或者多个维度都需要独立的进行扩展
当类型进行扩展时,它自带品牌;当品牌扩展时,它自带类型。
案例:
package com.model.bridge;
/**
* 品牌类
*/
public interface Brand {
void info();
}
/**
* 苹果品牌
*/
public class Apple implements Brand{
@Override
public void info() {
System.out.println("苹果");
}
}
/**
* 联想品牌
*/
public class Lenovo implements Brand{
@Override
public void info() {
System.out.println("联想");
}
}
/**
* 抽象的电脑类型类
*/
public abstract class Computer {
/**
* 组合 品牌 桥
*/
protected Brand brand;
public Computer(Brand brand) {
this.brand = brand;
}
public void info(){
brand.info(); //自带品牌
}
}
class Desktop extends Computer{
public Desktop(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("笔记本电脑 ");
}
}
public class Test {
/**
* 测试类
*/
public static void main(String[] args) {
//苹果笔记本
Computer computer = new Laptop(new Apple());
computer.info();
System.out.println("===================");
//联想台式机
Computer computer2 = new Desktop(new Lenovo());
computer2.info();
}
}
结果: