java 设计模式之初探装饰者模式

  • 应用场景:想为一个类动态的加上一些功能.
  • 设计模式之开闭原则:只对实现类的修改.不对接口进行修改.
//装饰和被装饰者都要实现的接口
public interface Sourceable {


    public void method();
}
//被装饰的类
public class Source  implements Sourceable{

    @Override
    public void method() {
        System.out.println("this is source method");

    }

}
//装饰类  可以动态的为source 添加一些功能
public class Decorator implements Sourceable{

    private Sourceable source;


    public Decorator(Sourceable source) {
        super();
        this.source = source;
    }


    @Override
    public void method() {

        System.out.println("decorator before");
        source.method();
        System.out.println("decorator after");

    }



}

测试类:

public class DecoratorTest {


    public static void main(String[] args) {
        Sourceable source =  new Source();

        Decorator d = new Decorator(source);
        d.method();

    }
}
decorator before
this is source method
decorator after

总结:
1.装饰和被装饰者实现了同一个接口
2.装饰者保留了一个被装饰者的引用

动态的为一个对象增加功能,而且还能动态撤销。(继承不能做到这一点,继承的功能是静态的,
不能动态增删。)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值