- The decorator pattern helps to add behavior or responsibilities to an object.
- This is also called “Wrapper”.
- Suppose we have some 6 objects and 2 of them need a special behavior, we can do this with the help of a decorator.
- Decorators should be abstract classes and the concrete implementation should be derived from them.
- Examples:
- Christmas tree : There is a need to decorate a Christmas tree. Now we have many branches which need to be decorated in different ways.
- Soft Cone Mixture
- Coffee Mixture
- Different Windows in a common window
Q. The "Adapter" pattern is also known as "Wrapper" pattern (WrapperPattern). Is Wrapper/Adapter/Decorator the same pattern?
A. No. AdapterPattern is used to convert the interface of an object into something else. DecoratorPattern is used to extend the functionality of an object while maintaining its interface. Both of these are probably sometimes called WrapperPattern since both of them do "wrap" an object.
Q. Decorator and Subclassing
A. Subclassing works fine but there are cases in which it is not appropriate or practical. If you want a behavior for several components, then you end up with many subclasses. As your code grows more complicated, having too many subclasses creates maintenance problems and makes your code more error-prone. You must also reproduce all of the parent class constructors that your subclass needs to support. In cases like this, it is better to use the Decorator pattern.
Difference that we see between a decorator pattern and subclassing is that we can decorate any class that implements an interface with a single class.
Example: A dress that you keep on making by adding features like emobroydree, satinlace etc.
public interface Dress {
public int cost = 0;
public int getCost();
}
public class SimpleDress implements Dress {
private int cost = 10;
public int getCost() {
return cost;
}
}
public abstract class DecoratorDress implements Dress {
protected Dress mydress;
DecoratorDress(Dress dress) {
mydress = dress;
}
public int getCost() {
return mydress.getCost();
}
}
public class Embroydree extends DecoratorDress {
private int cost = 20;
public Embroydree(Dress dress) {
super(dress);
cost = cost + dress.getCost();
}
public int getCost() {
return cost;
}
}
public class SatinLace extends DecoratorDress {
private int cost = 20;
public SatinLace(Dress dress) {
super(dress);
cost = cost + dress.getCost();
}
public int getCost() {
return cost;
}
}
public class Client {
public static void main( String [] args) {
Dress newDress = new SimpleDress();
newDress = new Embroydree(newDress);
newDress = new SatinLace(newDress);
System.out.println("Cost : " + newDress.getCost());
}
}
No comments:
Post a Comment