1. Background
The decoration mode adds a new function to an object and modifies it based on the object. The function implemented in This article is that object a has a way to show and output "This is a test". After decoration, It outputs "This is a test for decorate ". Essentially, multiple classes use one interface, and the class to be modified is defined in the constructor of the modifier class.
2. Code Implementation
(1) first, create a common interface with the show () method ()
package Decorate;public interface Component { public void show();}
(2) create a class to implement show
package Decorate;public class Concrete implements Component{ public void show(){ System.out.print(This is a test); }}
(3) create the decorate implementation class
package Decorate;public class Decorate implements Component { Component component; public Decorate(Component c){ component=c; } public void show(){ component.show(); System.out.print( for decorate); }}
(4) Client usage
package Decorate;public class Client { public static void main(String[] args){ Component a=new Concrete(); Component b=new Decorate(a); a.show(); System.out.println(); b.show(); }}
Result