设计模式-装饰器模式Decorator(结构型)

作者 : admin 本文共1441个字,预计阅读时间需要4分钟 发布时间: 2024-06-17 共1人阅读

装饰器模式(Decorator)

装饰器模式是一种结构模式,通过装饰器模式可以在不改变原有类结构的情况下向一个新对象添加新功能,是现有类的包装。

图解设计模式-装饰器模式Decorator(结构型)插图

角色

  1. 抽象组件:定义组件的抽象方法
  2. 具体组件:实现组件的抽象方法
  3. 抽象装饰器:实现抽象组件接口,聚合具体组件
  4. 具体装饰器:定义装饰方法,重写抽象组件的抽象方法,并在方法内调用具体组件的方法实现和装饰方法

代码示例

抽象组件:

public interface Shape {
    void paint();
}

具体组件:

public class Rotundity implements Shape {
    @Override
    public void paint() {
        System.out.println("画了一个圆形");
    }
}

public class Triangle implements Shape{
    @Override
    public void paint() {
        System.out.println("画了一个三角形");
    }
}

抽象装饰器

public abstract class ShapeDecorator implements Shape{
    protected Shape shape;

    public ShapeDecorator(Shape shape) {
        this.shape = shape;
    }
}

具体装饰器

/** 颜色装饰*/
public class ColorDecorator extends ShapeDecorator{
    public ColorDecorator(Shape shape) {
        super(shape);
    }
    @Override
    public void paint() {
        shape.paint();
        filling();
    }
    private void filling(){
        System.out.println("并填充颜色");
    }
}
/** 字体装饰*/
public class FontDecorator extends ShapeDecorator{
    public FontDecorator(Shape shape) {
        super(shape);
    }

    @Override
    public void paint() {
        shape.paint();
        changePaint();
    }
    public void changePaint(){
        System.out.println("并加粗了字体");
    }
}

使用

public class Test {
    public static void main(String[] args) {
        Shape triangle = new Triangle();
        Shape rotundity = new Rotundity();
        Shape triangleColorDecorator = new ColorDecorator(triangle);
        Shape rotundityColorDecorator = new ColorDecorator(rotundity);
        System.out.println("画一个三角形,并填充颜色:");
        triangleColorDecorator.paint();
        System.out.println("画一个圆形,并填充颜色,在加粗字体:");
        FontDecorator fontDecorator = new FontDecorator(rotundityColorDecorator);
        fontDecorator.paint();
    }
}
画一个三角形,并填充颜色:
画了一个三角形
并填充颜色
画一个圆形,并填充颜色,在加粗字体:
画了一个圆形
并填充颜色
并加粗了字体
本站无任何商业行为
个人在线分享 » 设计模式-装饰器模式Decorator(结构型)
E-->