装饰设计模式
装饰模式:动态的给一个对象增加一些额外的职责,就增加对象功能来说,装饰模式好比生成子类实现更为灵活。装饰模式是一种对象结构型模式.
![](https://img.haomeiwen.com/i1871780/3bd3a0522d7e4c94.png)
使用场景
- 在不影响其他对象的情况下,以动态,透明得到方式给单个对象添加职责.
- 当不能采用继承的方式对系统进行扩展或者采用继承不利于系统的扩展和维护的时可以采用使用装饰门模式。
代码案例:
Component
interface Component {
public void operation();
}
Decorator
public class Decorator implements Component {
private Component component;//维持一个对抽象构件对象的引用
public Decorator(Component component) {
this.component = component;
}
@Override
public void operation() {
component.operation();
}
}
ConcreteDecorator
public class ConcreteDecorator extends Decorator {
public ConcreteDecorator(Component component) {
super(component);
}
@Override
public void operation() {
super.operation();//调用原有业务方法
addedBehavior();
}
//新业务增加的方法
private void addedBehavior() {
}
}
优点
- 对于扩展一个对象的功能,装设模式比集成模式更加的灵活性,不会导致类的个数急剧增加.
- 动态的方式来扩展一个对象的功能
- 可以对一个对象进行多次的装饰,通过使用不同的具体的装饰类以及这些装饰类的排列组合.
虽然比继承的方式,更加的灵活,但是出错的概率更加的大了。
在andrid中运用
context类族在装饰模式的运用.
ContextWrapper
![](https://img.haomeiwen.com/i1871780/fd2f7a1cf81ab464.png)
![](https://img.haomeiwen.com/i1871780/eea9a0d8d13fc2d5.png)
具体讲的实现在ContextImp
![](https://img.haomeiwen.com/i1871780/31c91db146a28b2f.png)
![](https://img.haomeiwen.com/i1871780/c0cde664540f32bb.png)
网友评论