裝飾器模式(Decorator Pattern)允許向一個現有的對象添加新的功能,同時又不改變其結構。這種類型的設計模式屬于結構型模式,它是作為現有的類的一個包裝。
這種模式創建了一個裝飾類,用來包裝原有的類,并在保持類方法簽名完整性的前提下,提供了額外的功能。
我們通過下面的實例來演示裝飾器模式的使用。其中,我們將把一個形狀裝飾上不同的顏色,同時又不改變形狀類。
實現
我們將創建一個 Shape 接口和實現了 Shape 接口的實體類。然后我們創建一個實現了 Shape 接口的抽象裝飾類ShapeDecorator,并把 Shape 對象作為它的實例變量。
RedShapeDecorator 是實現了 ShapeDecorator 的實體類。
DecoratorPatternDemo,我們的演示類使用 RedShapeDecorator 來裝飾 Shape 對象。
步驟 1
創建一個接口。
Shape.java
1
2
3
4
|
public interface Shape { void draw(); } |
步驟 2
創建實現接口的實體類。
Rectangle.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
|
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
1
2
3
4
5
6
7
8
9
10
11
12
|
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
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
|
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
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
|
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
驗證輸出。
1
2
3
4
5
6
7
8
9
10
|
Circle with normal border Shape: Circle Circle of red border Shape: Circle Border Color: Red Rectangle of red border Shape: Rectangle Border Color: Red |
感謝閱讀,希望能幫助到大家,謝謝大家對本站的支持!