23种设计模式——桥接模式
1.视频链接:
https://www.bilibili.com/video/BV1mc411h719?p=8&vd_source=870c050a66e5b4971e571ca9ad8cb7dd
2.桥接模式:将抽象部分与它的实现部分分离,使他们都可以独立地变化。它是一种对象结构型模式,又称为柄体模式或接口模式
3.由图可以看出,电脑有品牌与类型两种职责,违背了单一职责原则
4.进入正题——桥接模式,将类型与品牌解耦,使得他们可以独立地变化
5.代码
Brand
public interface Brand { void info(); }
Apple
public class Apple implements Brand{ @Override public void info() { System.out.print("苹果"); } }
Lenovo
public class Lenovo implements Brand{ @Override public void info() { System.out.print("联想"); } }
Computer
public abstract class Computer { //将Brand品牌属性通过这种方式组合到Computer类中 protected Brand brand; public Computer(Brand brand) { this.brand = brand; } public void info(){ brand.info(); } }
Desktop
class Desktop extends Computer { public Desktop(Brand brand) { super(brand); } @Override public void info() { super.info(); System.out.println("台式机"); } }
Laptop
class Laptop extends Computer { public Laptop(Brand brand) { super(brand); } @Override public void info() { super.info(); System.out.println("笔记本"); } }
Test
Computer computer=new Desktop(new Lenovo()); computer.info(); System.out.println("---------------------------------------------------"); Computer computer1=new Laptop(new Apple()); computer1.info();
6.运行结果
好啦!到这里就结束了,欢迎小伙伴指出问题!
下一篇:
Java 简单实现单向链表反转