裝飾器模式(Decorator Pattern)允許向一個(gè)現(xiàn)有的對(duì)象添加新的功能,同時(shí)又不改變其結(jié)構(gòu)。這種類(lèi)型的設(shè)計(jì)模式屬于結(jié)構(gòu)型模式,它是作為現(xiàn)有的類(lèi)的一個(gè)包裝。
這種模式創(chuàng)建了一個(gè)裝飾類(lèi),用來(lái)包裝原有的類(lèi),并在保持類(lèi)方法簽名完整性的前提下,提供了額外的功能。
我們通過(guò)下面的實(shí)例來(lái)演示裝飾器模式的使用。其中,我們將把一個(gè)形狀裝飾上不同的顏色,同時(shí)又不改變形狀類(lèi)。
實(shí)現(xiàn)
我們將創(chuàng)建一個(gè) Shape 接口和實(shí)現(xiàn)了 Shape 接口的實(shí)體類(lèi)。然后我們創(chuàng)建一個(gè)實(shí)現(xiàn)了 Shape 接口的抽象裝飾類(lèi)ShapeDecorator,并把 Shape 對(duì)象作為它的實(shí)例變量。
RedShapeDecorator 是實(shí)現(xiàn)了 ShapeDecorator 的實(shí)體類(lèi)。
DecoratorPatternDemo,我們的演示類(lèi)使用 RedShapeDecorator 來(lái)裝飾 Shape 對(duì)象。
步驟 1
創(chuàng)建一個(gè)接口。
Shape.java
public interface Shape { void draw();} 步驟 2
創(chuàng)建實(shí)現(xiàn)接口的實(shí)體類(lèi)。
Rectangle.java
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
創(chuàng)建實(shí)現(xiàn)了 Shape 接口的抽象裝飾類(lèi)。
ShapeDecorator.java
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 類(lèi)的實(shí)體裝飾類(lèi)。
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"); }}步驟 5
使用 RedShapeDecorator 來(lái)裝飾 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(); }} 步驟 6
驗(yàn)證輸出。
Circle with normal borderShape: CircleCircle of red borderShape: CircleBorder Color: RedRectangle of red borderShape: RectangleBorder Color: Red
感謝閱讀,希望能幫助到大家,謝謝大家對(duì)本站的支持!
新聞熱點(diǎn)
疑難解答
圖片精選
網(wǎng)友關(guān)注