装饰模式文本显示组件类
时间: 2023-06-23 16:07:57 浏览: 55
好的,下面给出一个基于装饰模式的文本显示组件类的示例代码。
```java
// 抽象组件类
interface TextComponent {
void display();
}
// 具体组件类
class PlainText implements TextComponent {
private String text;
public PlainText(String text) {
this.text = text;
}
@Override
public void display() {
System.out.print(text);
}
}
// 抽象装饰类
abstract class TextDecorator implements TextComponent {
private TextComponent textComponent;
public TextDecorator(TextComponent textComponent) {
this.textComponent = textComponent;
}
@Override
public void display() {
textComponent.display();
}
}
// 具体装饰类:加粗
class BoldTextDecorator extends TextDecorator {
public BoldTextDecorator(TextComponent textComponent) {
super(textComponent);
}
@Override
public void display() {
System.out.print("<b>");
super.display();
System.out.print("</b>");
}
}
// 具体装饰类:斜体
class ItalicTextDecorator extends TextDecorator {
public ItalicTextDecorator(TextComponent textComponent) {
super(textComponent);
}
@Override
public void display() {
System.out.print("<i>");
super.display();
System.out.print("</i>");
}
}
```
这个示例中,`PlainText` 是具体的组件类,`TextDecorator` 是装饰类,`BoldTextDecorator` 和 `ItalicTextDecorator` 是具体的装饰类。
使用示例:
```java
TextComponent text = new BoldTextDecorator(new ItalicTextDecorator(new PlainText("Hello, world!")));
text.display(); // 输出:<b><i>Hello, world!</i></b>
```
在这个示例中,我们首先创建了一个 `PlainText` 实例,然后用 `ItalicTextDecorator` 和 `BoldTextDecorator` 对它进行了装饰,最终得到的文本组件 `text` 就是加粗且斜体的 "Hello, world!"。当我们调用 `text.display()` 时,输出的 HTML 标签将被正确嵌套,形成一个完整的文本表示。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![docx](https://img-home.csdnimg.cn/images/20210720083331.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)
![](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)