结构型-装饰器decorator
2020-04-28 本文已影响0人
程序男保姆
- 定义
装饰器模式(Decorator Pattern)允许向一个现有的对象添加新的功能,同时又不改变其结构。这种类型的设计模式属于结构型模式,它是作为现有的类的一个包装。decaroty类不仅继承核心类 并且还组合了核心类
- 优点
装饰类和被装饰类可以独立发展,不会相互耦合,装饰模式是继承的一个替代模式,装饰模式可以动态扩展一个实现类的功能。
1、扩展一个类的功能。 2、动态增加功能,动态撤销。
- 缺点
多层装饰比较复杂。
此例为不改变画什么形状类的情况下 动态的为形状添加颜色
类图
image.png
/***
* 形状接口
*/
public abstract class AbstractShape {
abstract void draw ();
}
public class CircleShape extends AbstractShape {
@Override
void draw() {
System.out.println("画圆形形状");
}
}
/***
* 长方形
*/
public class RectangleShape extends AbstractShape {
@Override
void draw() {
System.out.println("画长方形形状");
}
}
public abstract class AbstractDecaratoryShape extends AbstractShape {
AbstractShape shape;
public AbstractDecaratoryShape(AbstractShape shape) {
this.shape = shape;
}
@Override
void draw() {
shape.draw();
}
}
public class BlueDecaratoryShapeImpl extends AbstractDecaratoryShape {
public BlueDecaratoryShapeImpl(AbstractShape shape) {
super(shape);
}
@Override
void draw() {
super.draw();
System.out.println("绿色的");
}
}
public class RedDecaratoryShapeImpl extends AbstractDecaratoryShape {
public RedDecaratoryShapeImpl(AbstractShape shape) {
super(shape);
}
@Override
void draw() {
super.draw();
System.out.println("红色的");
}
}
public class Test {
public static void main(String[] args) {
AbstractShape shape = new CircleShape();
shape.draw();
System.out.println();
shape= new RedDecaratoryShapeImpl(shape);
shape.draw();
System.out.println();
shape = new BlueDecaratoryShapeImpl(shape);
shape.draw();
System.out.println();
}
}