Шаблон проектирования декоратора в примере Java
Шаблон проектирования Decorator используется для изменения функциональности объекта во время выполнения. В то же время другие экземпляры того же класса не будут затронуты этим, поэтому отдельный объект получает измененное поведение. Шаблон проектирования декоратора — это один из шаблонов структурного проектирования (например, композиция для реализации.
Шаблон оформления декоратора
-
Component Interface - The interface or abstract class defining the methods that will be implemented. In our case
Car
will be the component interface.package com.journaldev.design.decorator; public interface Car { public void assemble(); }
-
Component Implementation - The basic implementation of the component interface. We can have
BasicCar
class as our component implementation.package com.journaldev.design.decorator; public class BasicCar implements Car { @Override public void assemble() { System.out.print("Basic Car."); } }
-
Decorator - Decorator class implements the component interface and it has a HAS-A relationship with the component interface. The component variable should be accessible to the child decorator classes, so we will make this variable protected.
package com.journaldev.design.decorator; public class CarDecorator implements Car { protected Car car; public CarDecorator(Car c){ this.car=c; } @Override public void assemble() { this.car.assemble(); } }
-
Concrete Decorators - Extending the base decorator functionality and modifying the component behavior accordingly. We can have concrete decorator classes as
LuxuryCar
andSportsCar
.package com.journaldev.design.decorator; public class SportsCar extends CarDecorator { public SportsCar(Car c) { super(c); } @Override public void assemble(){ super.assemble(); System.out.print(" Adding features of Sports Car."); } }
package com.journaldev.design.decorator; public class LuxuryCar extends CarDecorator { public LuxuryCar(Car c) { super(c); } @Override public void assemble(){ super.assemble(); System.out.print(" Adding features of Luxury Car."); } }
Шаблон проектирования декоратора — диаграмма классов
Программа тестирования шаблонов декоратора
package com.journaldev.design.test;
import com.journaldev.design.decorator.BasicCar;
import com.journaldev.design.decorator.Car;
import com.journaldev.design.decorator.LuxuryCar;
import com.journaldev.design.decorator.SportsCar;
public class DecoratorPatternTest {
public static void main(String[] args) {
Car sportsCar = new SportsCar(new BasicCar());
sportsCar.assemble();
System.out.println("\n*****");
Car sportsLuxuryCar = new SportsCar(new LuxuryCar(new BasicCar()));
sportsLuxuryCar.assemble();
}
}
Обратите внимание, что клиентская программа может создавать различные типы объектов во время выполнения, а также указывать порядок выполнения. Вывод приведенной выше тестовой программы:
Basic Car. Adding features of Sports Car.
*****
Basic Car. Adding features of Luxury Car. Adding features of Sports Car.
Шаблон проектирования декоратора — важные моменты
- Шаблон проектирования Декоратор полезен для предоставления возможностей модификации во время выполнения и, следовательно, более гибок. Его легко поддерживать и расширять, когда количество вариантов больше.
- Недостаток шаблона проектирования декоратор заключается в том, что в нем используется множество объектов одного вида (декораторов).
- Шаблон декоратора часто используется в FileReader, BufferedReader и т. д.