天天看點

Java23種設計模式——裝飾模式透明裝飾模式半透明裝飾模式

該系列文章為部落客學習筆記,原文請參考參考連接配接

本文禁止轉載,但是歡迎大家留言區留言交流[微笑]

透明裝飾模式

今天研究了一下裝飾者模式,簡單談一談對其了解就是通過一個裝飾類(Decorator)将基本操作類和增強操作類連接配接起來,将兩者分開來。

并且在這個裝飾類(Decorator)保留對基本操做類進行關聯,使其在進行擴充操作的同時可以調用基本操作。

流程圖:

Java23種設計模式——裝飾模式透明裝飾模式半透明裝飾模式

基本操作就比如說對文字設定顔色,而拓展操作是在設定完文字顔色的基礎上設定背景顔色,比如說Button為了顯示出為按鈕可以為背景設定灰色,而TextView是文本,可以為背景色設定成透明色。

這裡裝飾類Decorator裡面關聯了Component對象,而基本操作類Color實作了Component對象,維護了一個指向基本操作的引用,通過該引用可以調用基本操作的對象。

擴充操作類(Button,TextView)泛化(繼承)了裝飾類,在裝飾類中并不增加增強操作,而是在他的子類中根據自身類不同的特點進行添加增強操作。

代碼:

public abstract  class Component
{
    public abstract void display();
}
           
public class ComponentDecorator extends Component {
    private Component component;

    public ComponentDecorator(Component component) {
        this.component = component;
    }

    @Override
    public void display() {
        component.display();
    }
}
           
public class BlackBorderDecorator extends ComponentDecorator {
    public BlackBorderDecorator(Component component) {
        super(component);
    }

    @Override
    public void display() {
        setBlackBorderDecorator();
        super.display();
    }

    private void setBlackBorderDecorator() {
        System.out.println("增加了背景顔色");
    }
}
           
public class ScrollBarDecorator extends ComponentDecorator {
    public ScrollBarDecorator(Component component) {
        super(component);
    }

    @Override
    public void display() {
        setScrollBarDecorator();
        super.display();
    }

    private void setScrollBarDecorator() {
        System.out.println("增加了滾動條");
    }
}
           
public class Window extends Component{
    @Override
    public void display() {
        System.out.println("顯示功能");
    }
}
           
public class MyClass {

    public static void main(String[] args) {
        Component component,componentBB,componentSB;
        component=new Window();
        componentBB=new ScrollBarDecorator(component);
        componentSB=new BlackBorderDecorator(componentBB);
        componentSB.display();
    }
}
           

輸出:

增加了背景顔色

增加了滾動條

顯示功能

以上采用的是裝飾者模式的透明模式,透明模式的意思是:要求用戶端程式不應該将對象聲明為具體的類,而應該全部聲明為Component類型。透明裝飾模式可以讓用戶端透明地使用裝飾之前的對象和裝飾之後的對象,無須關心它們的差別,此外,還可以對一個已裝飾過的對象進行多次裝飾,得到更為複雜、功能更為強大的對象。

半透明裝飾模式

簡單舉個例子,比如我們需要在類ScrollBarDecorator中增加方法

private void setDelete(){
        System.out.println("删除滾動條");
    }
           

但是我就想單獨調用他,但是我們的用戶端全部都是面向抽象類程式設計,裡面并沒有setDelete() 方法。

是以我們隻能對用戶端進行如下更改:

public class MyClass {

    public static void main(String[] args) {
        Component component;
        ScrollBarDecorator componentSB;
        component=new Window();
        componentSB=new ScrollBarDecorator(component);
        componentSB.setDelete();
    }
}
           

半透明性可以對額外的一些方法進行調用,靈活性很大,但是缺點是不能對同一對象多次裝飾。

我認為不能對統一對象多次裝飾是因為你可能新增加的方法(setDelete)沒有調用父類,并且你Component接口中也沒有這個方法,是以無法在向上裝飾。

微信公衆号:

Java23種設計模式——裝飾模式透明裝飾模式半透明裝飾模式

QQ群:365473065