装饰器模式(Decorator Pattern),为原有的类增加新的功能。
装饰器设计模式与适配器模式的区别
适配器模式:将一个接口转变成另一个接口,即需要改变原有类的接口方式。目的是通过改变接口来达到重复使用的目的。java 适配器设计模式_wh来啦的博客-CSDN博客
装饰器设计模式:不改变被装饰对象的接口,而是保持原有的接口,即不改变原有的类。增强原有对象的功能,或改变原有对象的处理方式而增提高性能。
举例说明,word文字可以改变各种颜色。
代码举例, 为car类和bus类添加新功能。
代码实现结果:
定义主函数:
package Decorator_Pattern; class Decorator_Pattern { public static void main(String[] args){ System.out.println("######原始car#########"); Transport car =new Car(); car.run(); System.out.println("#####加入装饰模式后的car########"); Transport transport_Car= new SpeedTransportdecorator(car); transport_Car.run(); System.out.println("--------------------------------------------------"); System.out.println("#####原始bus#######"); Transport bus = new Bus(); bus.run(); System.out.println("#####加入装饰模式后的bus########"); Transport transport= new SpeedTransportdecorator(new Bus()); transport.run(); } }
定义car类,bus类,及其父类。
class Transport{ void run(){} } class Car extends Transport{ void run () { System.out.println("I am car, I can run"); } } class Bus extends Transport{ void run () { System.out.println("I am bus, I can run,xixi"); } }
定义适配器的类,其父类继承Transport类,其子类实现具体增加的功能。
class Transportdecorator extends Transport{ Transport transport; Transportdecorator(Transport transport){} void run(){ transport.run(); speedup(); } void speedup(){} }
定义适配器子类,具体实现需要增加的功能。
class SpeedTransportdecorator extends Transportdecorator { Transport transport; SpeedTransportdecorator(Transport transport){ super(transport); this.transport = transport; } void run(){ transport.run(); speedup(); } void speedup(){ System.out.println("I'm going to speed up"); } }
完整代码:
package Decorator_Pattern; class Decorator_Pattern { public static void main(String[] args){ System.out.println("######原始car#########"); Transport car =new Car(); car.run(); System.out.println("#####加入装饰模式后的car########"); Transport transport_Car= new SpeedTransportdecorator(car); transport_Car.run(); System.out.println("--------------------------------------------------"); System.out.println("#####原始bus#######"); Transport bus = new Bus(); bus.run(); System.out.println("#####加入装饰模式后的bus########"); Transport transport= new SpeedTransportdecorator(new Bus()); transport.run(); } } class Transport{ void run(){} } class Car extends Transport{ void run () { System.out.println("I am car, I can run"); } } class Bus extends Transport{ void run () { System.out.println("I am bus, I can run,xixi"); } } class Transportdecorator extends Transport{ Transport transport; Transportdecorator(Transport transport){} void run(){ transport.run(); speedup(); } void speedup(){} } class SpeedTransportdecorator extends Transportdecorator { Transport transport; SpeedTransportdecorator(Transport transport){ super(transport); this.transport = transport; } void run(){ transport.run(); speedup(); } void speedup(){ System.out.println("I'm going to speed up"); } }