设计模式之---装饰模式

in #steemit7 years ago

java的io流体系的设计就是用的装饰模式,知道这一点再看io流体系会又豁然开朗的感觉!

装饰模式(Decorator Pattern)

定义

Attach additional responsibilities to an object dy-namically keeping the same interface. Decorators provide a flex-ible alternative to subclassing for extending functionality.
装饰模式指的是在不必改变原类文件和使用继承的情况下,动态地扩展一个对象的功能。它是通过创建一个包装对象,也就是装饰来包裹真实的对象。

类图 略 参看百度

从类图可以看出装饰模式拥有四个功能类

  • 抽象构件类
  • 具体构件类
  • 装饰类
  • 具体装饰类

优点

  • 装饰类与被装饰类解耦和
  • 装饰模式弥补和改善了继承类间的强耦合关系

缺点

  • 装饰类膨胀会给项目维护带来不便

代码

public abstract class Component {
    public abstract void operate();
}
public class ConcreteCompenent  extends Component{

    public void operate() {
        System.out.println("ConcreteCompenent");
  }
}
public abstract class Decorator extends Component {
    private Component component=null;
 public Decorator(Component component){
        this.component=component;
  }
    @Override
  public void operate() {
        this.component.operate();
  }
}
public class ConcreteDecorator1 extends Decorator {

    public ConcreteDecorator1(Component component) {
        super(component);
  }
    private void method1(){
        System.out.println("method1");
  }
    public  void operate(){
        this.method1();
 super.operate();
  }

}
public class ConcreteDecorator2 extends Decorator {
    public ConcreteDecorator2(Component component) {
        super(component);
  }
    private void method2(){
        System.out.println("method2");
  }
    public void opertate(){
        this.method2();
 super.operate();
  }
}
public class Test {
    public static void main(String[] args) {
        Component component=new ConcreteCompenent();
  component=new ConcreteDecorator1(component);
  component.operate();
  component=new ConcreteDecorator2(component);
  component.operate();
  }
}

##运行结果

method1
ConcreteCompenent
method1
ConcreteCompenent