//创建一个接口publicinterfaceShape{
voiddraw();}//创建实现接口的实体类。publicclassRectangleimplementsShape{
@Overridepublicvoiddraw(){
System.out.println("Shape: Rectangle");}}publicclassCircleimplementsShape{
@Overridepublicvoiddraw(){
System.out.println("Shape: Circle");}}//创建实现了 Shape 接口的抽象装饰类。publicabstractclassShapeDecoratorimplementsShape{
protected Shape decoratedShape;publicShapeDecorator(Shape decoratedShape){
this.decoratedShape = decoratedShape;}publicvoiddraw(){
decoratedShape.draw();}}//创建扩展了 ShapeDecorator 类的实体装饰类publicclassRedShapeDecoratorextendsShapeDecorator{
publicRedShapeDecorator(Shape decoratedShape){
super(decoratedShape);}@Overridepublicvoiddraw(){
decoratedShape.draw();setRedBorder(decoratedShape);}privatevoidsetRedBorder(Shape decoratedShape){
System.out.println("Border Color: Red");}}//使用 RedShapeDecorator 来装饰 Shape 对象。publicclassDecoratorPatternDemo{
publicstaticvoidmain(String[] args){
Shape circle =newCircle();
ShapeDecorator redCircle =newRedShapeDecorator(newCircle());
ShapeDecorator redRectangle =newRedShapeDecorator(newRectangle());//Shape redCircle = new RedShapeDecorator(new Circle());//Shape redRectangle = new RedShapeDecorator(new Rectangle());
System.out.println("Circle with normal border");
circle.draw();
System.out.println("\nCircle of red border");
redCircle.draw();
System.out.println("\nRectangle of red border");
redRectangle.draw();}}//执行程序,输出结果:
Circle with normal border
Shape: Circle
Circle of red border
Shape: Circle
Border Color: Red
Rectangle of red border
Shape: Rectangle
Border Color: Red