设计模式---装饰模式
参考:http://blog.csdn.net/surprisesdu/article/details/605965
http://www.iteye.com/topic/121149
一、装饰模式(Decorator)
动态地给一个对象添加一些额外的职责,就增加功能来说,装饰模式比生成子类更加灵活,它是继承的一种替代方案。
与继承的对比:
都能实现功能的扩展,而装饰模式使用的是组合,避免了使用过多继承造成系统的复杂性增加。
二、四个角色
抽象接口:给客户端提供功能接口
具体类:实现抽象接口,具体的原始功能类
装饰角色类:实现抽象接口,持有具体类的对象
具体的装饰类:继续装饰角色类,具体的扩展功能,里面可以增加新的功能
三、程序示例
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
//抽象接口:给客户端提供功能接口 public interface Component { void show(); //(实现特长展示功能) }
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
//具体的类:实现接口 class ConcreteComponent implements Component { public void show() { System.out.println("------我的特长-------"); System.out.println("我会讲笑话"); } }
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
//装饰类:实现接口 class Decorator implements Component { private Component component; public Decorator() { } public Decorator(Component component) { this.component = component; } public void show() { if (component != null) { component.show(); } } }
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
//具体的装饰类:继承装饰类,可以增加新的功能 class ConcreteDecorator extends Decorator { public ConcreteDecorator() {} public ConcreteDecorator(Component component) { super(component); } public void show() { super.show(); addShowDance(); } //新增加的功能 public void addShowDance() { System.out.println("我会跳舞!"); } }
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
//具体的装饰类2:继承装饰类,可以增加新的功能 class ConcreteDecorator_2 extends Decorator { public ConcreteDecorator_2() {} public ConcreteDecorator_2(Component component) { super(component); } public void show() { super.show(); addShowSing(); } //新增加的功能 public void addShowSing() { System.out.println("我会唱歌!"); } }
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
public class TestMain { public static void main(String[] args) { Component user = new ConcreteComponent(); user.show(); Decorator userDec1 = new ConcreteDecorator(user); userDec1.show(); Decorator userDec2 = new ConcreteDecorator_2(userDec1); //Decorator userDec2 = new ConcreteDecorator_2(user); userDec2.show(); } }