栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

结构型设计模式---桥接设计模式

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

结构型设计模式---桥接设计模式

一、问题

商场系统中常见的商品分类,以电脑为类,怎么处理商品分类销售的问题?

 

①可以使用多继承结构来分类

 图解:

使用继承的方式,不管新增一个电脑类型还是新增一个电脑品牌,都会牵扯出另外一个维度的变化,这样就会产生很大很多的类。

二、桥接模式

处理多层继承结构,处理多维度变化的场景,将各个维度设计成独立的继承结构,使各个维度可以独立的扩展在抽象层建立关联。

 

三、案例

1.类图

代码实现;

package 桥接模式;
//维度1:电脑品牌
abstract class Brand {
    abstract void sale();
}
//联想电脑
class Lenove extends Brand{
    @Override
    void sale() {
        System.out.println("联想");
    }
}
//戴尔电脑
class Dell extends Brand{
    @Override
    void sale() {
        System.out.println("戴尔");
    }
}
//神州电脑
class Shenzhou extends Brand{
    @Override
    void sale() {
        System.out.println("神州");
    }
}
class Computer{
protected Brand brand;
Computer(Brand brand){
    this.brand=brand;
}
void sale(){
    brand.sale();
}
}
//维度2:电脑类型
//台式
class Desktop extends Computer{
    Desktop(Brand brand){
        super(brand);
    }
    void sale(){
        super.sale();
        System.out.println("出售台式电脑");
    }
}
//笔记本
class Laptop extends Computer{
    Laptop(Brand brand){
        super(brand);
    }
    void sale(){
        super.sale();
        System.out.println("出售笔记本电脑");
    }
}
//客户类
public class Test {
    public static void main(String[] args) {
        Computer computer1 =new Desktop(new Lenove());
        computer1.sale();
        Computer computer2 =new Desktop(new Dell());
        computer2.sale();
    }
}

 

 

 

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/978040.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号