首页 > 代码库 > 设计模式(八) : 结构型模式--装饰模式

设计模式(八) : 结构型模式--装饰模式

装饰模式的目的是为了给一个对象动态的增加一些功能。装饰对象和被装饰的对象实现同一个接口,装饰对象持有被装饰对象的实例。

类图:

示意性代码:

package com.javadesignpattern.Decorator;

public interface Component {
    
    void sampleOperation();

}
package com.javadesignpattern.Decorator;

public class ConcreteComponent implements Component{

    public void sampleOperation() {
        // TODO Auto-generated method stub
        System.out.println(ConcreteComponent.class + ": sampleOperation function");
    }
}
package com.javadesignpattern.Decorator;

public class Decorator implements Component{
    
    Component component;
    
    public Decorator(Component component){
        this.component = component;
    }
    

    public void sampleOperation() {
        // TODO Auto-generated method stub
        component.sampleOperation();
        System.out.println(Decorator.class + " : sampleOperation function");
    }

}
package com.javadesignpattern.Decorator;

public class ConcreteDecorator extends Decorator{
    Decorator dec;
    
    public ConcreteDecorator(Decorator dec){
        super(dec.component);
        this.dec = dec;
    }
    
    public void sampleOperation(){
        super.sampleOperation();
        System.out.println(ConcreteDecorator.class + " : sampleOperation function");
    }

}
package com.javadesignpattern.Decorator;

public class Client {
    
    public static void main(String[] ags){
        Component componemt = new Decorator(new ConcreteComponent());
        componemt.sampleOperation();        
        System.out.println("--------------------");
        
        Component componemt1 = new ConcreteDecorator(new Decorator(new ConcreteComponent()));
        componemt1.sampleOperation();
        System.out.println("--------------------");
    }

}

装饰模式以这样的形式出现:

new Decorator1(new Decorator2(new Decorator3(new ConcreteComponent())))

装饰模式在什么场景下使用:

1. 需要扩展一个类的功能

2. 动态的给一个对象增加一些功能

3. 需要一些扩展类的功能,但是有很多类,这样使得继承变得不太现实。