This Pattern is used to extend the functionality of an object dynamically without having to change
the original class source or using inheritance. This is accomplished by creating an object wrapper
referred to as Decorator around the actual object.
Component Interface: The interface or abstract class defining the methods that will be implemented.
Component Implementation: The basic implementation of the component interface
Decorator: Decorator class implements the component interface and it has a HAS-A relationship
with the component interface. The component variable should be accessible to the child decorator
classes.
Concrete Decorator: Extending the base decorator functionality and modifying the component behavior according.
Usage in java:
used a lot in Java IO classes, such as FileReader, BufferedReader.
概念复杂,代码很简单.
-
package decorator;
-
-
interface Icecream{
-
public String makeIceCream();
-
}
-
-
class SimpleIceCream implements Icecream{
-
@Override
-
public String makeIceCream(){
-
return "Base - IceCream";
-
}
-
}
-
-
class IceCreamDecorator implements Icecream{
-
protected Icecream specialIcecream;
-
-
public IceCreamDecorator(Icecream specialIcecream){
-
this.specialIcecream = specialIcecream;
-
}
-
-
@Override
-
public String makeIceCream(){
-
return specialIcecream.makeIceCream();
-
}
-
}
-
-
-
//Concrete Decorator
-
class NuttyDecorator extends IceCreamDecorator{
-
-
public NuttyDecorator(Icecream specialIcecream){
-
super(specialIcecream);
-
}
-
-
@Override
-
public String makeIceCream(){
-
return specialIcecream.makeIceCream()+addNuts();
-
}
-
-
private String addNuts(){
-
return " + Cruncky Nuts";
-
}
-
}
-
-
-
//Concrete Decorator
-
class HoneyDecorator extends IceCreamDecorator{
-
public HoneyDecorator(Icecream IceCreamDecorator){
-
super(IceCreamDecorator);
-
}
-
-
@Override
-
public String makeIceCream(){
-
return specialIcecream.makeIceCream()+addHoney();
-
}
-
-
private String addHoney(){
-
return " + Sweet Honey";
-
}
-
}
-
-
public class DecoratorPatternDemo {
-
public static void main(String[] args){
-
Icecream ic = new HoneyDecorator(new NuttyDecorator(new SimpleIceCream()));
-
System.out.println(ic.makeIceCream());
-
}
-
}
阅读(561) | 评论(0) | 转发(0) |