java模式之装饰模式的学习

来源:互联网 发布:中国就业率数据 编辑:程序博客网 时间:2024/05/22 12:37

装饰模式使用情景:

需要扩展一个类的功能,或给一个类增加附加功能。

需要动态地给一个对象增加功能,这些功能可以再动态地撤销。

需要增加由一些基本功能的排列组合而产生的非常大量的功能,从而使继承关系变得不现实。

示例:

package test;

public interface PubliInterface {
    public void operation();

}

package test;

public class PubliInterfaceimpl implements PubliInterface{

    public void operation() {
        System.out.println("doSomething");
        
    }

}

package test;

public class Decorator implements PubliInterface{
    private PubliInterface component = null;

    public void operation() {
    if(component!=null){
        component.operation();
        addBehavior();
        
    }    
        
    }

    public Decorator(PubliInterface component) {
        super();
        this.component = component;
    }
    
    public void addBehavior(){
        System.out.println("增加的行为");
    }
    public static void main(String[] args) {
         Decorator de = new  Decorator(new PubliInterfaceimpl());
         de.operation();
    }

}

/**输出结果:

doSomething
增加的行为

**/

总结:


1、装饰模式实际就是新建一个类2、重写原接口方法在实现原本想实现的功能的基础上,增加新的功能作为元接口的实现类

0 0
原创粉丝点击