Android开发经验谈Android开发Android技术知识

Android 装饰者模式

2019-02-13  本文已影响13人  Yink_Liu

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 代理模式很像,有的人容易混淆,其实区别的他们很简单。这两个模式他们都会拥有一个对象。但是代理模式更强调的是代理二字。代理它的功能,而不是扩展,不对功能进行增强。装饰者模式则重点在装饰二字上。给原有的对象添加(装饰)新的功能。

上一篇下一篇

猜你喜欢

热点阅读