7.装饰器模式
个人理解,装饰器模式是为了实现修改原代码而实现增加或删除对象的内部功能的一种设计模式。
看一下装饰器模式的实现——这个例子来自漫画设计模式:什么是 “装饰器模式” ?_程序员小灰的博客-优快云博客。
public interface Car {
void run();
}
public class BenzCar implements Car{
@Override
public void run() {
System.out.println("奔驰开车了!");
}
}
public class BmwCar implements Car{Car
@Override
public void run() {
System.out.println("宝马开车了!");
}
}
public class TeslaCar implements Car{
@Override
public void run() {
System.out.println("特斯拉开车了!");
}
}
到这里为止,这几种车实现了Car接口。
public abstract class CarDecorator implements Car {
protected Car decoratedCar;
public CarDecorator(Car decoratedCar){
this.decoratedCar = decoratedCar;
}
public void run(){
decoratedCar.run();
}
}
装饰抽象类,也实现了Car接口,只不过内置了一个Car对象,run方法调用内置的Car的对象的run方法
public class AutoCarDecorator extends CarDecorator {
public AutoCarDecorator(Car decoratedCar){
super(decoratedCar);
}
@Override
public void run(){
decoratedCar.run();
autoRun();
}
private void autoRun(){
System.out.println("开启自动驾驶");
}}
AutoCarDecorator继承了抽象装饰器CarDecorator,重写了run方法,在run方法中增加了一个功能,fly()方法。实现了开放——闭合原则。
如果我们要继续增加功能,只需要在写一个继承AutoCarDecorator的子类,重写run方法,增加新功能。
如果我们要实现其他功能,而不要自动驾驶功能,则如下。
public class FlyCarDecorator extends CarDecorator {
public FlyCarDecorator(Car decoratedCar){
super(decoratedCar);
}
@Override
public void run(){
decoratedCar.run();
fly();
}
private void fly(){
System.out.println("开启飞行汽车模式");
}
}
public class Client {
public static void main(String[] args) {
Car benzCar = new BenzCar();
Car bmwCar = new BmwCar();
Car teslaCar = new TeslaCar();
//创建自动驾驶的奔驰汽车
CarDecorator autoBenzCar = new AutoCarDecorator(benzCar);
//创建飞行的、自动驾驶的宝马汽车
CarDecorator flyAutoBmwCar = new FlyCarDecorator(new AutoCarDecorator(bmwCar));
benzCar.run();
bmwCar.run();
teslaCar.run();
autoBenzCar.run();
flyAutoBmwCar.run();
}
}
1338





