IPerson:
/** * @author com.tiantian * @version 创建时间:2012-11-20 下午3:43:04 */public interface IPerson { public void canDo();}
Person:
/** * @author com.tiantian * @version 创建时间:2012-11-20 下午3:44:04 */public class Person implements IPerson{ @Override public void canDo() { System.out.println("I can code"); }}
Decorator(所有Person装饰者的父类):
/** * @author com.tiantian * @version 创建时间:2012-11-20 下午3:44:55 */public class Decorator implements IPerson{ private IPerson person; public Decorator(IPerson person) { this.person = person; } @Override public void canDo() { person.canDo(); }}
DecoratorSwim(Swim装饰--为Peron添加“Swim”功能):
/** * @author com.tiantian * @version 创建时间:2012-11-20 下午3:48:54 */public class DecoratorSwim extends Decorator{ public DecoratorSwim(IPerson person) { super(person); } @Override public void canDo() { super.canDo(); System.out.println("I also can swim"); }}
DecoratorDraw(Draw装饰--为Peron添加“Draw”功能):
/** * @author com.tiantian * @version 创建时间:2012-11-20 下午3:47:29 */public class DecoratorDraw extends Decorator{ public DecoratorDraw(IPerson person) { super(person); } @Override public void canDo() { super.canDo(); System.out.println("I also can draw"); }}
Test:
/** * @author com.tiantian * @version 创建时间:2012-11-20 下午3:49:35 */public class Test { public static void main(String[] args) { Decorator decorator = new DecoratorDraw(new DecoratorSwim(new Person())); decorator.canDo(); }}