前言
本章讲解设计模式中装饰器设计模式的相关知识
方法
1.概念
与桥接模式类似,该模式也是为了解决类爆炸的问题。但是装饰器模式关注于功能的扩展,真实的角色比较稳定。桥接模式的真实角色在多维度之间不断的变化,具有不确定性。
2.装饰器模式的实现思路
1)新建相应工程
其中,Car(车)为基本对象,Feature接口为Car类具有的基本功能,SuperCar类为装饰类。
ACar,AACar,AAACar为三种不同特性的车。
2)代码展示
Car:
package decorator;
/**
* 真实对象-普通汽车类
* 更高级的车为ACar、AACar、AAACar以此类推
* @author jwang
*
*/
public class Car implements Feature{
@Override
public void move() {
System.out.println("普通车行走");
}
}
Feature:
package decorator;
public interface Feature {
/**
* 车辆行驶方法
*/
public void move();
}
SuperCar:
package decorator;
/**
* 装饰器类,用来扩充基本对象的功能
* @author jwang
*
*/
public class SuperCar implements Feature{
private Feature car;
public SuperCar(Feature car) {
super();
this.car = car;
}
@Override
public void move() {
car.move();
}
}
其中一种特性车ACar:
package decorator;
public class ACar extends SuperCar {
public ACar(Feature car) {
super(car);
}
//A类车新特性
public void A(){
System.out.println("A类汽车还可以飞");
}
@Override
public void move() {
super.move();
A();
}
}
由此可见,A类车可以通过传递过来的类型任意的扩充自己的功能。
3)编写测试代码测试
Test:
package decorator;
public class Test {
public static void main(String[] args) {
//普通车的行走方式
Car car = new Car();
car.move();
System.out.println("-----------------------");
//普通车加入A类车行走的优势
ACar aCar = new ACar(car);
aCar.move();
System.out.println("-----------------------");
//普通车加入AA类车行走的优势
AACar aaCar = new AACar(car);
aaCar.move();
System.out.println("-----------------------");
//普通车加入AA类车行走的优势和AAA类车行走的优势
AACar aaCar2 = new AACar(new AAACar(car));
aaCar2.move();
}
}
程序执行结果: