用Java写一个装饰器模式
时间: 2023-07-18 17:27:49 浏览: 58
装饰器模式是一种常用的设计模式,用于为对象动态添加行为。下面是使用Java语言实现装饰器模式的示例:
首先,我们定义一个接口`Shape`,代表形状对象:
```java
public interface Shape {
void draw();
}
```
然后,我们实现`Rectangle`类和`Circle`类,它们都实现了`Shape`接口,分别表示矩形和圆形:
```java
public class Rectangle implements Shape {
public void draw() {
System.out.println("Shape: Rectangle");
}
}
public class Circle implements Shape {
public void draw() {
System.out.println("Shape: Circle");
}
}
```
接下来,我们定义一个抽象类`ShapeDecorator`,它也实现了`Shape`接口,并包含一个`Shape`对象,用于扩展其行为:
```java
public abstract class ShapeDecorator implements Shape {
protected Shape decoratedShape;
public ShapeDecorator(Shape decoratedShape) {
this.decoratedShape = decoratedShape;
}
public void draw() {
decoratedShape.draw();
}
}
```
最后,我们实现具体的装饰器类,例如`RedShapeDecorator`,它继承了`ShapeDecorator`类,并添加了一个红色的边框:
```java
public class RedShapeDecorator extends ShapeDecorator {
public RedShapeDecorator(Shape decoratedShape) {
super(decoratedShape);
}
public void draw() {
decoratedShape.draw();
setRedBorder(decoratedShape);
}
private void setRedBorder(Shape decoratedShape) {
System.out.println("Border Color: Red");
}
}
```
最后,我们可以创建一个客户端程序来测试装饰器模式:
```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();
}
}
```
输出结果如下:
```
Circle with normal border
Shape: Circle
Circle of red border
Shape: Circle
Border Color: Red
Rectangle of red border
Shape: Rectangle
Border Color: Red
```
通过使用装饰器模式,我们可以在不改变原有代码的情况下,动态地为对象添加行为。在上述示例中,`RedShapeDecorator`类充当了装饰器,用于添加红色的边框。
相关推荐
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)