设计模式装饰模式

1.装饰模式的定义及使用场景
定义:
装饰模式也称为包装模式,结构型设计模式之一,其使用一种对客户端透明的方式来动态地扩展对象的功能,同时它也是继承关系的一种替代方案之一。动态地给一个对象添加一些额外的职责。就增加功能来说,装饰模式相比生成子类更为灵活
使用场景:
需要扩展一个类的功能,或给一个类增加附加功能
需要动态地给一个对象增加功能,这些功能可以再动态地撤销
需要为一批的兄弟类进行改装或加装功能,当然是首选装饰模式

《设计模式装饰模式》 Paste_Image.png

2. 装饰模式的优缺点

2.1优点

装饰类和被装饰类可以独立发展,而不会相互耦合。换句话说,Component类无需知道Decorator类,Decorator类是从外部来扩展Component类的功能,而Decorator也不用知道具体的构件

装饰模式是继承关系的一个替代方案。我们看装饰类Decorator,不管装饰多少层,返回的对象还是component,实现的还是is-a的关系

装饰模式可以动态地扩展一个实现类的功能

2.2缺点

对于装饰模式,多层装饰是比较复杂的。因尽量减少装饰类的数量,以便减低系统的复杂度。

3. 装饰模式的实现方式

public abstract  class Component {
    public abstract void operator();
}```

public class ConcreteComponent extends Component {
@Override
public void operator() {
System.out.println(“ConcreteComponent operator”);
}
}“`

public class Decorator extends Component {
    private Component component;
    Decorator(Component component) {
        this.component = component;
    }
    @Override
    public void operator() {
        if (component != null) {
            component.operator();
        }
    }
}```

public class ConcreteDecorator1 extends Decorator {
public ConcreteDecorator1(Component component) {
super(component);
}
private void method1() {
System.out.println(“method1 修饰”);
}
@Override
public void operator() {
super.operator();
method1();
}
}“`

public class ConcreteDecorator2 extends Decorator {
    public ConcreteDecorator2(Component component) {
        super(component);
    }
    private void method2() {
        System.out.println("method2 修饰");
    }
    @Override
    public void operator() {
        super.operator();
        method2();
    }
}```

public class Test {
public static void main(String args[]) {
Component component = new ConcreteComponent();
ConcreteDecorator1 decorator1 = new ConcreteDecorator1(component);
ConcreteDecorator2 decorator2 = new ConcreteDecorator2(component);
decorator1.operator();
decorator2.operator();
}
}“`
4. 装饰模式在Android中的实际应用
Context类本身是一个纯abstract类,他有两个具体的实现子类:ContextImpl和ContextWrapper。其中ContextWrapper类,只是一个包装而已,ContextWrapper构造函数中必须包含一个真正的Context引用,同时ContextWrapper提供了attachBaseContext()用于给ContextWrapper对象中指定真正的Context对象,调用ContextWrapper的方法都会被转向其所包含的真正的Context对象。
ContextThemeWrapper类,其内部包含了与主题(Theme)相关的接口,这里所说的主题就是指在AndroidMainifest.xml中通过android:theme为Application元素或者Activity元素指定的主题。当然,只有Activity才需要主题,Service是不需要主题的,Application同理。
而ContextImpl类则真正实现了Context中的所有函数,应用程序中所调用的各种Context类的方法,其实现均来于该类。Context的两个子类分工明确,其中ContextImpl是Context的具体实现类,ContextWrapper是Context的包装类。
详见 Android之Context底层原理,http://blog.csdn.net/junbin1011/article/details/54612858
出处:http://huangjunbin.com/page/2/

    原文作者:GB_speak
    原文地址: https://www.jianshu.com/p/b7843d525d25
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞