Definition: Dynamically attaches responsibility to an object. To extend functionality, decorators provide a more resilient alternative than inheritance.
UML diagram:
code example: Take my favorite ice cream as an example
/** Definition Ice Cream abstract class */
Public abstract class Ice {
Description
???? Public String desctription = "Unkonw";
???? Get Description
???? Public abstract String getdestription ();
???? Billing
???? public abstract double Cost ();
???? Print
???? public void print () {
???????? System.out.println (getdestription () + "/" + cost ());
????}
}
?
/** Milk Ice cream * *
public class Milkice extends ice{
???? Public Milkice () {
???????? TODO auto-generated Constructor stub
???????? Desctription = "milk";
????}
[Email protected]
???? public double cost () {
???????? TODO auto-generated Method Stub
???????? return 2.0d;
????}
[Email protected]
???? Public String getdestription () {
???????? TODO auto-generated Method Stub
???????? return desctription;
????}
}
?
/**
* define Ice cream decorator */
Public abstract class Icedecorator extends ice{
???? protected Ice mIce = null;
???? Public icedecorator (Ice ice) {
???????? TODO auto-generated Constructor stub
???????? MIce = ice;
????}
}
?
/** Strawberry Seasoning * *
public class Strawberrydecorator extends icedecorator{
???? Public strawberrydecorator (Ice ice) {
???????? Super (ICE);
???????? TODO auto-generated Constructor stub
????}
[Email protected]
???? Public String getdestription () {
???????? TODO auto-generated Method Stub
???????? return mice.getdestription () + "strawberry";
????}
[Email protected]
???? public double cost () {
???????? TODO auto-generated Method Stub
???????? return Mice.cost () + 0.5d;
????}
}
?
/** Chocolate Seasoning * *
public class Chocolatedecorator extends icedecorator{
???? Public chocolatedecorator (Ice ice) {
???????? Super (ICE);
???????? TODO auto-generated Constructor stub
????}
[Email protected]
???? Public String getdestription () {
???????? TODO auto-generated Method Stub
???????? return mice.getdestription () + "chocolate";
????}
[Email protected]
???? public double cost () {
???????? TODO auto-generated Method Stub
???????? return Mice.cost () + 0.8d;
????}
}
?
public class Main {
???? public static void Main (string[] args) {
???????? Ice Strawberry_milk = new Milkice ();// Definition Milk Strawberry ice cream
???????? Ice Chocolate_milk = new Milkice ();// define Milk chocolate ice cream
???????? Strawberry_milk = new Strawberrydecorator (strawberry_milk);// Add Strawberry decoration
???????? Chocolate_milk = new Chocolatedecorator (chocolate_milk);// Add chocolate decoration
???????? Strawberry_milk.getdestription ();
???????? Strawberry_milk.cost ();
???????? Chocolate_milk.getdestription ();
???????? Chocolate_milk.cost ();
????????
???????? Strawberry_milk.print ();
???????? Chocolate_milk.print ();
????}
}
Printing results:
milkstrawberry/2.5
milkchocolate/2.8
Design Pattern-Decorator