Adorner mode (decorator pattern) allows new functionality to be added to an existing object without altering its structure. This type of design pattern is a structural pattern and is a wrapper for an existing class.
This pattern creates a decorative class that wraps the original class and provides additional functionality while preserving the integrity of the class method signature.
We demonstrate the use of the adorner pattern through the example below. In which, we will decorate a shape with a different color, while not changing the shape class.
Realize
We will create a shape interface and an entity class that implements the shape interface. We then create an abstract decorative class shapedecorator that implements the shape interface and take the Shape object as its instance variable.
Redshapedecorator is the entity class that implements the Shapedecorator.
Decoratorpatterndemo, our Demo class uses Redshapedecorator to decorate a Shape object.
Step 1
Create an interface.
Shape.java
Public interface Shape {
void Draw ();
}
Step 2
Creates an entity class that implements an interface.
Rectangle.java
public class Rectangle implements shape {
@Override public
Void Draw () {
System.out.println ("Shape: Rectangle ");
}
}
Circle.java public
class Circle implements the Shape {
@Override public
Void Draw () {
System.out.println ( "Shape:circle");
}
Step 3
Creates an abstract decorative class that implements the Shape interface.
Shapedecorator.java
Public abstract class Shapedecorator implements shape {
protected shape decoratedshape;
Public Shapedecorator (Shape decoratedshape) {
this.decoratedshape = decoratedshape;
}
public void Draw () {
decoratedshape.draw ();
}
}
Step 4
Create an entity decoration class that extends from the Shapedecorator class.
Redshapedecorator.java
public class Redshapedecorator extends Shapedecorator {public
redshapedecorator (Shape decoratedshape) {
Super (Decoratedshape);
}
@Override public
Void Draw () {
decoratedshape.draw ();
Setredborder (Decoratedshape);
}
private void Setredborder (Shape decoratedshape) {
System.out.println ("Border color:red");
}
Step 5
Use Redshapedecorator to decorate a Shape object.
Decoratorpatterndemo.java
public class Decoratorpatterndemo {public
static void Main (string[] args) {
Shape circle = new Circle ();
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 ();
}
Step 6
Verify the output.
Circle with normal border
shape:circle
Circle of red border
shape:circle Border color:red Rectangle of Red border
shape:rectangle
border color:red
Thank you for reading, I hope to help you, thank you for your support for this site!