当前位置: 移动技术网 > IT编程>开发语言>Java > 详解java装饰模式(Decorator Pattern)

详解java装饰模式(Decorator Pattern)

2019年07月22日  | 移动技术网IT编程  | 我要评论

一、装饰器模式(decorator pattern)

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

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

我们通过下面的实例来演示装饰器模式的使用。其中,我们将把一个形状装饰上不同的颜色,同时又不改变形状类。

二、实现
我们将创建一个 shape 接口和实现了 shape 接口的实体类。然后我们创建一个实现了 shape 接口的抽象装饰类shapedecorator,并把 shape 对象作为它的实例变量。

redshapedecorator 是实现了shapedecorator 的实体类。

decoratorpatterndemo,我们的演示类使用 redshapedecorator 来装饰 shape 对象。

步骤 1
创建一个接口。

shape.java

public interface shape {
  void draw();
}

步骤 2
创建实现接口的实体类。

rectangle.java

public class rectangle implements shape {
 
  @override
  public void draw() {
   system.out.println("shape: rectangle");
  }
}


circle.java

public class circle implements shape {
 
  @override
  public void draw() {
   system.out.println("shape: circle");
  }
} 

步骤 3
创建实现了 shape 接口的抽象装饰类。

shapedecorator.java

public abstract class shapedecorator implements shape {
  protected shape decoratedshape;
 
  public shapedecorator(shape decoratedshape){
   this.decoratedshape = decoratedshape;
  }
 
  public void draw(){
   decoratedshape.draw();
  }  
} 

步骤 4
创建扩展自 shapedecorator 类的实体装饰类。

redshapedecorator.java

public class redshapedecorator extends shapedecorator {
 
  public redshapedecorator(shape decoratedshape) {
   super(decoratedshape);    
  }
 
  @override
  public void draw() {
   decoratedshape.draw();     
   setredborder(decoratedshape);
  }
 
  private void setredborder(shape decoratedshape){
   system.out.println("border color: red");
  }
} 

步骤 5
使用 redshapedecorator 来装饰 shape 对象。

decoratorpatterndemo.java

public class decoratorpatterndemo {
  public static void main(string[] args) {
 
   shape circle = new circle();
 
   shape redcircle = new redshapedecorator(new circle());
 
   shape redrectangle = new redshapedecorator(new rectangle());
   system.out.println("circle with normal border");
   circle.draw();
 
   system.out.println("\ncircle of red border");
   redcircle.draw();
 
   system.out.println("\nrectangle of red border");
   redrectangle.draw();
  }
} 

步骤 6
验证输出。

circle with normal border
shape: circle

circle of red border
shape: circle
border color: red

rectangle of red border
shape: rectangle
border color: red

希望本文所述对大家学习java程序设计有所帮助。

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网