JAVA 装饰者模式

文章目录

介绍

装饰者模式

实现

介绍

描述

装饰器模式设计模式属于结构型模式,是允许向一个现有的对象添加新的功能,进行多次包装,同时又不改变其结构。

特点

优点:装饰模式可以动态扩展一个实现类的功能。

缺点:多层装饰比较复杂。

实现原理

通常为了扩展一个类的功能经常使用继承方式实现,随着功能的增多,就会导致子类太多,为了在不增加许多子类的情况下扩展类,将拓展功能设置为新的类通过继承/实现 + 组合原本类的方式实现拓展。

适用

  1. 扩展一个类的功能。

  2. 动态增加功能,动态撤销。

装饰者模式

实现

第一步:创建抽象类Shape,做为被装饰对象,Circle、Rectangle为子类。

public abstract class Shape {

    private String type;
    private String des;

    public String getType() {
        return type;
    }

    public void setType(String type) {
        this.type = type;
    }

    public String getDes() {
        return des;
    }

    public void setDes(String des) {
        this.des = des;
    }

    public abstract String now();
}

// 子类
public class Circle extends Shape{
    public Circle() {
        setType("圆形");
        setDes("初始化圆形 ");
    }

    @Override
    public String now() {
        return super.getDes();
    }
}

// 子类 
public class Rectangle extends Shape{
    public Rectangle() {
        setType("矩形");
        setDes("初始化矩形");
    }

    @Override
    public String now() {
        return super.getDes();
    }
}

第二步:创建装饰者Decorator,继承+组合Shape类,Border、Color做为继承子类对原对象进行拓展。

// 创建装饰类 继承+ 组合
public class Decorator extends Shape{
    private Shape shape;

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

    @Override
    public String now() {
        // 重写 返回 原对象  + 当前描述
        return shape.getDes()+ " && " +  super.getDes();
    }

    @Override
    public String getDes() {
        // 重写 des
        return shape.getDes() + " && " + super.getDes();
    }
}

// 装饰子类
public class Border extends Decorator{
    public Border(Shape shape) {
        super(shape);
        setDes("添加 2cm 边框");
    }
}
// 装饰子类
public class Color extends Decorator{
    public Color(Shape shape) {
        super(shape);
        setDes(" 染绿色");

    }
}

第三步:测试。

public class Test {
    public static void main(String[] args) {
        Shape shape = new Circle();  // 创建被装饰对象
        System.out.println(shape.now());  // 输出现在样式
        shape = new Border(shape);  // 进行 边框装饰 
        System.out.println(shape.now()); // 输出现在样式
        shape = new Color(shape);  // 再次进行 颜色装饰
        System.out.println(shape.now()); // 输出现在样式
        //  初始化圆形 
        //  初始化圆形  && 添加 2cm 边框
        //  初始化圆形  && 添加 2cm 边框 &&  染绿色
    }
}

 

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值