一、裝飾器模式(Decorator Pattern)
允許向一個現(xiàn)有的對象添加新的功能,同時又不改變其結(jié)構(gòu)。這種類型的設(shè)計(jì)模式屬于結(jié)構(gòu)型模式,它是作為現(xiàn)有的類的一個包裝。
這種模式創(chuàng)建了一個裝飾類,用來包裝原有的類,并在保持類方法簽名完整性的前提下,提供了額外的功能。
我們通過下面的實(shí)例來演示裝飾器模式的使用。其中,我們將把一個形狀裝飾上不同的顏色,同時又不改變形狀類。
二、實(shí)現(xiàn)
我們將創(chuàng)建一個 Shape 接口和實(shí)現(xiàn)了 Shape 接口的實(shí)體類。然后我們創(chuàng)建一個實(shí)現(xiàn)了 Shape 接口的抽象裝飾類ShapeDecorator,并把 Shape 對象作為它的實(shí)例變量。
RedShapeDecorator 是實(shí)現(xiàn)了ShapeDecorator 的實(shí)體類。
DecoratorPatternDemo,我們的演示類使用 RedShapeDecorator 來裝飾 Shape 對象。
步驟 1
創(chuàng)建一個接口。
Shape.java
1
2
3
|
public interface Shape { void draw(); } |
步驟 2
創(chuàng)建實(shí)現(xiàn)接口的實(shí)體類。
Rectangle.java
1
2
3
4
5
6
7
|
public class Rectangle implements Shape { @Override public void draw() { System.out.println( "Shape: Rectangle" ); } } |
Circle.java
1
2
3
4
5
6
7
|
public class Circle implements Shape { @Override public void draw() { System.out.println( "Shape: Circle" ); } } |
步驟 3
創(chuàng)建實(shí)現(xiàn)了 Shape 接口的抽象裝飾類。
ShapeDecorator.java
1
2
3
4
5
6
7
8
9
10
11
|
public abstract class ShapeDecorator implements Shape { protected Shape decoratedShape; public ShapeDecorator(Shape decoratedShape){ this .decoratedShape = decoratedShape; } public void draw(){ decoratedShape.draw(); } } |
步驟 4
創(chuàng)建擴(kuò)展自 ShapeDecorator 類的實(shí)體裝飾類。
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
驗(yàn)證輸出。
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 |
希望本文所述對大家學(xué)習(xí)java程序設(shè)計(jì)有所幫助。