解析:

概念:装饰器模式又名包装(Wrapper)模式。装饰器模式以对客户端透明的方式拓展对象的功能,是继承关系的一种替代方案。

 

实现:

interface Sourceable{
    public void method();
}


//本来Source方法继承了Sourceable实现了method()方法

class Source implements Sourceable{
    @Override
    public void method(){
        System.out.println("the original method");
    }

}


//Decorator持有Sourceable的属性,对其进行装饰

class Decorator implements Sourceable{
    private Sourceable source;

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

    @Override
    public void method(){
        Sytem.out.println("before decorator!");
        source.method();
        System.out.println("after decorator!");
    }
}


 

public class DesignModel{
    public static void main(String args[]){
        //接口不能单独的实例化,必须通过实现类来帮助实例化
        Sourceable source = new Source();
        Sourceable obj = new Decorator(source);
        obj.method();
    }
}

 

最后修改于 2020-03-29 15:01:28
如果觉得我的文章对你有用,请随意赞赏
扫一扫支付
上一篇