标签:pre 抽象类 system http 装饰器 stat 技术 span 核心
在不修改原先对象核心的功能的情况下,对功能进行增强。
2.通过装饰模式,将方法增强。如图
car :被装饰的抽象类
package javadesign.decorate; /** * 抽象小汽车 */ public interface Car { public void buildCar(); }
benCar:被装饰的实现
package javadesign.decorate; public class BenCar implements Car { @Override public void buildCar() { System.out.println("建造一辆车"); } }
Decorator:装饰的类
package javadesign.decorate; public class Decorator implements Car { public Car car; public Decorator(Car car){ this.car=car; } @Override public void buildCar() { this.car.buildCar(); } }
StrongDecorator:装饰的实现
package javadesign.decorate; public class Decorator implements Car { public Car car; public Decorator(Car car){ this.car=car; } @Override public void buildCar() { this.car.buildCar(); } }
Client:测试类
package javadesign.decorate; public class Client { public static void main(String[] args) { Car car=new BenCar(); Decorator decorator=new StrongDecorator(car); ((StrongDecorator) decorator).buildSportsCar(); ((StrongDecorator) decorator).buildHouseCar(); } }
测试结果:
总结:装饰模式在不改变原先核心功能的情况下,可以实现增强,并且不会产生很多继承类,按照业务模块划分,通过不同的方法进行装饰。
标签:pre 抽象类 system http 装饰器 stat 技术 span 核心
原文地址:https://www.cnblogs.com/blogxiao/p/11206509.html