更新時(shí)間:2022-12-09 10:00:38 來源:動(dòng)力節(jié)點(diǎn) 瀏覽894次
裝飾器模式允許用戶在不改變其結(jié)構(gòu)的情況下向現(xiàn)有對(duì)象添加新功能。這種類型的設(shè)計(jì)模式屬于結(jié)構(gòu)模式,因?yàn)檫@種模式充當(dāng)現(xiàn)有類的包裝器。
此模式創(chuàng)建了一個(gè)裝飾器類,它包裝了原始類并提供了保持類方法簽名完整的附加功能。
我們通過以下示例演示裝飾器模式的使用,在該示例中我們將使用某種顏色裝飾形狀而不更改形狀類。
我們將創(chuàng)建一個(gè)Shape接口和實(shí)現(xiàn)Shape接口的具體類。然后我們將創(chuàng)建一個(gè)抽象裝飾器類ShapeDecorator實(shí)現(xiàn)Shape接口并將Shape對(duì)象作為其實(shí)例變量。
RedShapeDecorator是實(shí)現(xiàn)ShapeDecorator的具體類。
DecoratorPatternDemo,我們的演示類將使用RedShapeDecorator來裝飾Shape對(duì)象。
創(chuàng)建一個(gè)接口。
形狀.java
public interface Shape {
void draw();
}
創(chuàng)建實(shí)現(xiàn)相同接口的具體類。
矩形.java
public class Rectangle implements Shape {
@Override
public void draw() {
System.out.println("Shape: Rectangle");
}
}
圈子.java
public class Circle implements Shape {
@Override
public void draw() {
System.out.println("Shape: Circle");
}
}
創(chuàng)建實(shí)現(xiàn)Shape接口的抽象裝飾器類。
ShapeDecorator.java
public abstract class ShapeDecorator implements Shape {
protected Shape decoratedShape;
public ShapeDecorator(Shape decoratedShape){
this.decoratedShape = decoratedShape;
}
public void draw(){
decoratedShape.draw();
}
}
創(chuàng)建擴(kuò)展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");
}
}
使用RedShapeDecorator裝飾Shape對(duì)象。
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();
}
}
驗(yàn)證輸出。
Circle with normal border
Shape: Circle
Circle of red border
Shape: Circle
Border Color: Red
Rectangle of red border
Shape: Rectangle
Border Color: Red
0基礎(chǔ) 0學(xué)費(fèi) 15天面授
有基礎(chǔ) 直達(dá)就業(yè)
業(yè)余時(shí)間 高薪轉(zhuǎn)行
工作1~3年,加薪神器
工作3~5年,晉升架構(gòu)
提交申請(qǐng)后,顧問老師會(huì)電話與您溝通安排學(xué)習(xí)
初級(jí) 202925
初級(jí) 203221
初級(jí) 202629
初級(jí) 203743