十一、装饰器模式

装饰器 Decorator 

容许向一个现有的对象添加新的功能,同时又不改变其结构。这种设计类型属于结构性模式,它是做为现有类的一个包装设计模式

这种设计模式建立了一个装饰类,用来包装原有的类,并在保持类方法签名完整的前提下,提供额外的功能。this

意图:动态滴给一个对象添加一些额外的职责,就增长功能来讲,装饰器相比于生成子类,更加灵活

何使使用装饰器: 在不想增长子类的状况下,扩展类spa

优势:装饰类和被装饰类能够独立发展,不会相互耦合,装饰模式是继承的一个替代模式,装饰模式能够动态扩展一个实现类的功能。设计

缺点:多层装饰比较复杂。code

使用场景: 一、扩展一个类的功能。 二、动态增长功能,动态撤销。component

 

 

//基础接口
public interface Component {
    
    public void biu();
}
//具体实现类
public class ConcretComponent implements Component {

    public void biu() {
        
        System.out.println("biubiubiu");
    }
}
//装饰类
public class Decorator implements Component {

    public Component component;
    
    public Decorator(Component component) {
        
        this.component = component;
    }
    
    public void biu() {
        
        this.component.biu();
    }
}
//具体装饰类
public class ConcreteDecorator extends Decorator {

    public ConcreteDecorator(Component component) {

        super(component);
    }

    public void biu() {
        
        System.out.println("ready?go!");
        this.component.biu();
    }
}
//使用装饰器
  Component component = new ConcreteDecorator(new ConcretComponent());
  component.biu();

  //console:
  ready?go!
  biubiubiu
相关文章
相关标签/搜索