对于装饰器模式,在我看来,就是通过另一个类为指定的类填加一个功能,这样实现在不提高耦合性的基础上,增加了其他的需求,但是装饰的其他需求太多后,所产生的装饰类相应也会变多,从而使整个系统的装饰类结构庞大起来。 网络上的专业解释: 装饰器模式允许向一个现有的对象添加新的功能,同时又不改变其结构,它是作为仙有泪的一个包装。这种模式创建了一个装饰类,用来包装原有的类,并在保持类方法签名完整性的前提下,提供了额外的功能 实例:把圆形装饰上不同的颜色,又不改变形状类。
1.创建形状接口以及圆形实现类
interface Shape {
void draw();
}
public class Circle implements Shape {
@Override
public void draw() {
System.out.println("draw a circle!!!");
}
}
2.创建装饰抽象类以及各个颜色的实现类
public abstract class ShapeDecorat implements Shape{
protected Shape shape;
public ShapeDecorat(Shape shape) {
super();
this.shape = shape;
}
public abstract void draw();
public abstract void setBorder();
}
//红色装饰类
public class RedDecoretor extends ShapeDecorat {
public RedDecoretor(Shape shape) {
super(shape);
}
@Override
public void draw() {
shape.draw();
setBorder();
}
@Override
public void setBorder() {
System.out.println("a red circle!!!");
}
}
//蓝色装饰类
public class BlueDecoretor extends ShapeDecorat {
public BlueDecoretor(Shape shape) {
super(shape);
}
@Override
public void draw() {
shape.draw();
setBorder();
}
@Override
public void setBorder() {
System.out.println("a blue circle!!!");
}
}
3.测试类
public class Test {
public static void main(String[] args) {
//创建圆形对象
Circle circle=new Circle();
//画红色圆形
RedDecoretor redCircle=new RedDecoretor(circle);
//画蓝色圆形
BlueDecoretor blueCircle=new BlueDecoretor(circle);
System.out.println("=======================");
circle.draw();
System.out.println("=======================");
redCircle.draw();
System.out.println("=======================");
blueCircle.draw();
}
}
4.后台输出
=======================
draw a circle!!!
=======================
draw a circle!!!
a red circle!!!
=======================
draw a circle!!!
a blue circle!!!