装饰者模式(Decorator Pattern)

概念

是指在不改变原有对象的基础上,将功能附加到对象上,提供了比继承更有弹性的替代方案(拓展原有对象功能),属于结构型设计模式

使用场景

1.用于拓展一个类的功能或给一个类添加附加职责
2.动态的给一个对象添加功能,这些功能可以再动态撤销。

实例

现场建一个抽象类型,比如蛋糕

public abstract class Cake {

    protected abstract String getMsg();

    protected abstract int price();
}

那么就会有一个基础蛋糕

public class BaseCake extends Cake {
    @Override
    protected String getMsg() {
        return "小蛋糕";
    }

    @Override
    protected int price() {
        return 5;
    }
}

再创建一个装饰器

public abstract class DecoratorCake extends Cake {

    public Cake cake;

    public DecoratorCake(Cake cake) {
        this.cake = cake;
    }

    @Override
    protected String getMsg() {
        return this.cake.getMsg();
    }

    @Override
    protected int price() {
        return this.cake.price();
    }
}

再来一个水果蛋糕装饰器

public class DecoratorFruitsCake extends DecoratorCake{


    public DecoratorFruitsCake(Cake cake) {
        super(cake);
    }

    @Override
    protected String getMsg() {
        return "一个水果"+super.getMsg();
    }

    @Override
    protected int price() {
        return 1+super.price();
    }
}

最后测试一下

public class Test {
    public static void main(String[] args) {
        Cake cake = new BaseCake();

        cake = new DecoratorFruitsCake(cake);
        System.out.println(cake.getMsg());
        System.out.println(cake.price());
        cake = new DecoratorFruitsCake(cake);
        System.out.println(cake.getMsg());
        System.out.println(cake.price());
    }
}

结果
一个水果小蛋糕
6
一个水果一个水果小蛋糕
7

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值