Java的装饰器模式是结构型模式的一种,目的是增强被装饰类的功能,在JDK中,IO就使用了装饰器模式。
下面是代码:
人的接口:
public interface Human {
void run();
}
男人:
public class Man implements Human {
@Override
public void run() {
System.out.println("人可以走");
}
}
超人:
/**
* 装饰类,可以把人进化为超人,然后增强run方法
*/
public class SuperMan implements Human {
private Human human;
SuperMan(Human human){
this.human = human;
}
private void fly(){
System.out.println("走的速度达到了就能飞了");
}
@Override
public void run() {
this.human.run();
this.fly();
}
}
测试代码:
public class DecoratorTest {
public static void main(String[] args) {
// 当人没有进化成超人的时候
Human man = new Man();
man.run();
// 把人进化装饰成超人
SuperMan superMan = new SuperMan(man);
//进化成超人的人,就能速度达到就能飞
superMan.run();
}
}
测试结果:
人可以走
人可以走
走的速度达到了就能飞了
装饰器模式就是为了增强某一个类,并且是在原来的类的功能不变的情况下。这在框架中应用很广,如果我们要升级某一项功能,原来的类是能正常运行的,如果我们改原来的代码,原来的类被成千上万个类引用,哪改一发而动全身,这个代价是很大的,装饰器模式可以为我们解决增强一个类,但是又不修改原来的类的解决方案。