当前位置: 移动技术网 > 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



感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!

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

相关文章:

验证码:
移动技术网