装饰器模式
内容参考 w3cschool
分类: 结构性设计模式
应用: 1L的水能用木桶盛放,也能用1L的铁桶盛放;一张相片可以用不同的相框进行装饰
目录
UML类图
用户告诉不同的装饰器(红色、蓝色、绿色)去修饰不同的对象:Circle、Rectangle
创建形状接口
Shape
public interface Shape {
/**
* 绘制图形
*/
void draw();
}
创建 形状实体类
Circle
public class Circle implements Shape{
@Override
public void draw() {
System.out.println("[Shape-Circle]");
}
}
Rectangle
public class Rectangle implements Shape{
@Override
public void draw() {
System.out.println("[Shape-Rectangle]");
}
}
创建形状的抽象修饰器
public abstract class ShapeDecorator implements Shape{
protected Shape shapeDecorator;
public ShapeDecorator(Shape shapeDecorator) {
this.shapeDecorator = shapeDecorator;
}
@Override
public void draw() {
shapeDecorator.draw();
}
}
创建红色的边框修饰器
public class RedShapeDecorator extends ShapeDecorator{
public RedShapeDecorator(Shape shapeDecorator) {
super(shapeDecorator);
}
@Override
public void draw() {
shapeDecorator.draw();
setRedBorder(shapeDecorator);
}
private void setRedBorder(Shape shapeDecorator){
System.out.println("<Border> Color Red");
}
}
测试执行
public class ExecuteMain {
public static void main(String[] args) {
Shape circle = new Circle();
Shape redCircle = new RedShapeDecorator(new Circle());
Shape redRectangle = new RedShapeDecorator(new Rectangle());
System.out.println("--------normal Circle--------");
circle.draw();
System.out.println("--------Red Border Circle--------");
redCircle.draw();
System.out.println("--------Red Border Rectangle--------");
redRectangle.draw();
}
}
--------normal Circle--------
[Shape-Circle]
--------Red Border Circle--------
[Shape-Circle]
<Border> Color Red
--------Red Border Rectangle--------
[Shape-Rectangle]
<Border> Color Red
Process finished with exit code 0