Android 裝飾者模式
Android 設計模式系列文章Android 23種設計模式
一、前言
裝飾者模式也稱為包裝模式,其使用一種對客戶端透明的方式動態的擴充套件物件功能。裝飾者模式也是繼承關係的替代方案之一。裝飾者模式是結構型設計模式。重點也在裝飾二字。
二、定義
裝飾模式指的是在不必改變原類檔案和使用繼承的情況下,動態地擴充套件一個物件的功能。它是通過建立一個包裝物件,也就是裝飾來包裹真實的物件。
三、例子
概念永遠是懵懂的,下面我們通過一個簡單的例子,理解何為裝飾者模式。
1、定義一個被裝飾者
先抽象出一個person,吃飯
public abstract class Person { public abstract void eat(); }
再定義小明
public class XiaoMing extends Person { private static final String TAG = XiaoMing.class.getSimpleName(); @Override public void eat() { Log.d(TAG,"eat"); } }
2、定義裝飾者
先抽象出裝飾者。
public abstract class Decorator extends Person{ private Person person; // 這裡是重點,必須持有一個被裝飾者物件。 public Decorator(Person person) { this.person = person; } @Override public void eat() { person.eat(); } }
然後實現裝飾者
public class ConcreteDecorator extends Decorator { private static final String TAG = ConcreteDecorator.class.getSimpleName(); public ConcreteDecorator(Person person) { super(person); } @Override public void eat() { dessert(); super.eat();// 拓展時,前後都可以加方法 drinkTea(); } // 裝飾方法,甜品 public void dessert() { Log.d(TAG,"dessert"); } // 裝飾方法,喝茶 public void drinkTea() { Log.d(TAG,"drink tea"); } }
裝飾者無非兩點,一:擁有被裝飾者物件,二:透明的拓展原本的方法(eat)。
3、呼叫
XiaoMing xiaoMing = new XiaoMing(); ConcreteDecorator concreteDecorator = new ConcreteDecorator(xiaoMing); concreteDecorator.eat();
輸出如下:
02-13 11:31:27.850 8373-8373/com.yink.designpattern.designpattern D/ConcreteDecorator: dessert 02-13 11:31:27.850 8373-8373/com.yink.designpattern.designpattern D/XiaoMing: eat 02-13 11:31:27.850 8373-8373/com.yink.designpattern.designpattern D/ConcreteDecorator: drink tea
裝飾者模式例子到此就完了。結構比較簡單,獲得被裝飾物件。新增新的功能。
四、寫在最後
裝飾者模式和我之前的講的Android 代理模式很像,有的人容易混淆,其實區別的他們很簡單。這兩個模式他們都會擁有一個物件。但是代理模式更強調的是代理二字。代理它的功能,而不是擴充套件,不對功能進行增強。裝飾者模式則重點在裝飾二字上。給原有的物件新增(裝飾)新的功能。