Decorator Pattern
The Decorator Pattern is used to add the additional functions or responsibilities to an object statically or dynamically. the Decorator is also know as wrapper Pattern.
Benefit and use of the Decorator Pattern
- Decorator is used to Add new function to an object without affecting other objects.
-
It is Provide an alternative to subclassing.
-
Decorator is Make a responsibility easily added and removed dynamically.
-
Decorator is More flexible than static inheritance.
-
It is make transparent to the object.
Example
package r4r;
import java.util.Random;
class Numeric {
public void print() {
System.out.println(new Random().nextInt());
}
}
class Decorate {
public Decorate() {
System.out.print("Random numbers: ");
//print the random selected number
new Numeric().print();
}
}
class SubNumbers extends Numeric{
public SubNumbers() {
super();
System.out.print("Random numbers: ");
print();
}
}
public class decoratortest {
public static void main(String[] args) {
new Decorate();
new SubNumbers();
}
}