装饰模式

2017-10-15  本文已影响3人  刘尔泽

概念

装饰模式:动态地给一个对象增加一些额外职责,就增加对象功能来说,装饰模式比生成子类实现更为灵活, 装饰模式是一种 对象结构型

使用场景

class Decorator implements Component
{
       private Component component;  //维持一个对抽象构件对象的引用
       public Decorator(Component component)  //注入一个抽象构件类型的对象
       {
              this.component=component;
       }

       public void operation()
       {
              component.operation();  //调用原有业务方法
              System.out.println("Father");
       }
}
interface Component {
    public void operation();
}

3

public class ss {
    public static void main(String[] args) {
        Decorator decorator = new Decorator(new Component() {
            @Override
            public void operation() {
                System.out.println("Component");
            }
        });
        decorator.operation();
    }
}

结果
Component
Father

在Android 中的应用

1.context 类 在 装饰模式的应用

Context 是个抽象类,具体实现 在 ContextWrapper 这个类中。

在看看

public class ContextWrapper extends Context {
Context mBase;
 @Override
    public void startActivity(Intent intent) {
        mBase.startActivity(intent);
    }
}
上一篇 下一篇

猜你喜欢

热点阅读