桥接模式

未使用桥接模式

image.png

问题

  • 扩展性问题
    如果要增加一个新的类型如手机,则要增加多个品牌下的类
  • 违反单一职责原则
    一个类:如联想笔记本,有两个引起这个类变化的原因

使用桥接模式

  • UML


    image.png
  • 代码实现

package com.amberweather.bridge;
/**
 * 机器类型
 * @author Administrator
 *
 */
public class Computer {
    protected Brand brand;
    
    public Computer(Brand brand) {
        super();
        this.brand = brand;
    }

    public void sale(){
        brand.sale();
    }
}
class Desktop extends Computer{
    public Desktop(Brand brand){
        super(brand);
    }
    public void sale(){
        brand.sale();
        System.out.println("销售台式机");
    }
}
class Laptop extends Computer{
    public Laptop(Brand brand){
        super(brand);
    }
    public void sale(){
        brand.sale();
        System.out.println("销售笔记本");
    }
}
package com.amberweather.bridge;
/**
 * 品牌
 * @author Administrator
 *
 */
public interface Brand{
    void sale();
}
class Lenovo implements Brand{
    public void sale(){
        System.out.println("销售联想");
    }
}
class Dell implements Brand{
    public void sale(){
        System.out.println("销售戴尔");
    }
}
package com.amberweather.bridge;
public class Client {
    public static void main(String[] args) {
        Computer c = new Laptop(new Dell());
        c.sale();
    }
}
image.png
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • 在正式介绍桥接模式之前,我先跟大家谈谈两种常见文具的区别,它们是毛笔和蜡笔。假如我们需要大中小3种型号的画笔,能够...
    justCode_阅读 1,872评论 0 7
  • 1 场景问题# 1.1 发送提示消息## 考虑这样一个实际的业务功能:发送提示消息。基本上所有带业务流程处理的系统...
    七寸知架构阅读 5,227评论 5 63
  • 目录 本文的结构如下: 引言 什么是桥接模式 模式的结构 典型代码 代码示例 优点和缺点 适用环境 模式应用 一、...
    w1992wishes阅读 1,867评论 0 6
  • 本文参考:http://www.oschina.net/question/1436074_140456 http:...
    端木轩阅读 3,664评论 0 5
  • 一、概述 使用场景商城系统中常见的商品分类,以电脑为类,如何良好的处理商品分类销售的问题? 实例我们看如下的类层次...
    yjaal阅读 293评论 0 0

友情链接更多精彩内容