裝飾器模式(Decorator Pattern)允許向一個現有的對象添加新的功能,同時又不改變其結構。這種類型的設計模式屬于結構型模式,它是作為現有的類的一個包裝。
這種模式創建了一個裝飾類,用來包裝原有的類,并在保持類方法簽名完整性的前提下,提供了額外的功能。
關鍵代碼: 1、Component 類充當抽象角色,不應該具體實現。 2、修飾類引用和繼承 Component 類,具體擴展類重寫父類方法。
優點:裝飾類和被裝飾類可以獨立發展,不會相互耦合,裝飾模式是繼承的一個替代模式,裝飾模式可以動態擴展一個實現類的功能。
缺點:多層裝飾比較復雜。
- 創建一個接口。
/**
* 1. 創建一個接口。
* @author mazaiting
*/
public interface Shape {
/**
* 畫畫
*/
void draw();
}
- 創建實現接口的實體類。
/**
* 2. 創建實現接口的實體類。
* @author mazaiting
*/
public class Circle implements Shape{
public void draw() {
System.out.println("Shape: Circle");
}
}
/**
* 2. 創建實現接口的實體類。
* @author mazaiting
*/
public class Rectangle implements Shape{
public void draw() {
System.out.println("Shape: Rectangle");
}
}
- 創建實現了 Shape 接口的抽象裝飾類。
/**
* 3. 創建實現了 Shape 接口的抽象裝飾類。
* @author mazaiting
*/
public abstract class ShapeDecorator implements Shape{
protected Shape decoratShape;
public ShapeDecorator(Shape decoratedShape){
this.decoratShape = decoratedShape;
}
public void draw() {
decoratShape.draw();
}
}
- 創建擴展了 ShapeDecorator 類的實體裝飾類。
/**
* 4. 創建擴展了 ShapeDecorator 類的實體裝飾類。
* @author mazaiting
*/
public class RedShapeDecorator extends ShapeDecorator{
public RedShapeDecorator(Shape decoratedShape) {
super(decoratedShape);
}
@Override
public void draw() {
decoratShape.draw();
setRedBorder(decoratShape);
}
private void setRedBorder(Shape decoratedShape){
System.out.println("Border Color: Red");
}
}
- 使用 RedShapeDecorator 來裝飾 Shape 對象。
/**
* 5. 使用 RedShapeDecorator 來裝飾 Shape 對象。
* @author mazaiting
*/
public class Client {
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();
}
}
- 打印結果
Circle with normal border
Shape: Circle
Circle of red border
Shape: Circle
Border Color: Red
Rectangle of red border
Shape: Rectangle
Border Color: Red