一、问题
商场系统中常见的商品分类,以电脑为类,怎么处理商品分类销售的问题?
①可以使用多继承结构来分类
图解:
使用继承的方式,不管新增一个电脑类型还是新增一个电脑品牌,都会牵扯出另外一个维度的变化,这样就会产生很大很多的类。
二、桥接模式
处理多层继承结构,处理多维度变化的场景,将各个维度设计成独立的继承结构,使各个维度可以独立的扩展在抽象层建立关联。
三、案例
1.类图
扫描二维码关注公众号,回复:
14346225 查看本文章

代码实现;
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();
}
}