一、概述
把抽象(abstraction)与行为实现(implementation)分离开来,从而可以保持各部分的独立性以及应对它们的功能扩展
二、情景描述
对于电脑的分类有许多种,按照品牌分,按照台式或者笔记本等等,如果采用简单的多重继承的方式,则每种组合都需要建立一个类,因此,我们可以把属性抽取分析出来,这样在实例化对象时,就可以随意组合属性,减少了类的创建。
三、代码
1.电脑品牌类
/*处理多层继承结构,处理多维度变化的场景,将各个维度设计成独立的继承模块,使各个维度可以独立的拓展在抽象层。
*
*将属性分离开
*
*维度分解 属性自由组合
*
*品牌
* */
public interface Brand {
void brand();
}
2.电脑类型类
public class Computer {
protected Brand brand;
public Computer(Brand brand) {
this.brand = brand;
}
public void sale(){
brand.brand();
}
}
3.ThinkPad品牌类
public class ThinkPad implements Brand{
@Override
public void brand() {
System.out.println("ThinkPad");
}
}
4.戴尔品牌类
public class Dell implements Brand{
@Override
public void brand() {
System.out.println("Dell");
}
}
5.台式机类
public class Desktop extends Computer {
public Desktop(Brand brand) {
super(brand);
}
@Override
public void sale() {
super.sale();
System.out.println("销售台式机");
}
}
6.笔记本类
public class Laptop extends Computer{
public Laptop(Brand brand) {
super(brand);
}
public void sale(){
super.sale();
System.out.println("销售笔记本");
}
}
6.测试类
public class Test {
public static void main(String[] args) {
Computer com = new Desktop(new THinkPad());
com.sale();
Computer delDeskTop = new Desktop(new Dell());
delDeskTop.sale();
}
}