装饰器,顾名思义,就是把一个对象的功能进行扩展,添加新的装饰,让它具有新的特性和功能,在实现生活中,有很多装饰器实现的例子,比如人类可以跑,但有一个超人它不仅可以跑,而且还可以飞,这时在不改变原对象基础上,需要为超人添加飞的动作,就可以使用装饰模式。
/** * 人类. */ public abstract class Human { private String name; public String getName() { return name; } public void setName(String name) { this.name = name; } public void run() { System.out.println("人类跑起来"); } }
/** * 超人. */ public class SuperMan extends Human { private String food; private String work; public SuperMan(String food, String work) { this.food = food; this.work = work; } }
/** * 飞行装饰器. */ public abstract class FlyDecorator extends Human { protected abstract void fly(); private Human human; public FlyDecorator(Human human) { this.human = human; } @Override public void run() { if (human != null) { human.run(); } fly(); } }
/** * 超人的飞机装饰器. */ public class SuperManFlyDecorator extends FlyDecorator { public SuperManFlyDecorator(Human human) { super(human); } @Override protected void fly() { System.out.println("超人会飞"); } }
Human human = new SuperMan("超人", "飞起来"); FlyDecorator flyDecorator = new SuperManFlyDecorator(human); flyDecorator.run();