装饰着模式
该模式挺难理解,想了快一晚上。。。才算有点眉目。。。然后照搬一些java.io类还有servlet里面的过滤器终于有所领悟。
使用接口实现,下面给出代码:
/** *//** *定义被装饰者 **/ public interface Human { public void wearClothes(); public void walkToWhere(); } /** *//** *定义装饰者是个抽象类 **/ public abstract class Decorator implements Human { private Human human; public Decorator(Human human){ this.human=human; } public void walkToWhere() { human.walkToWhere(); } public void wearClothes() { human.wearClothes(); } } /** *//** *定义三种装饰,这是第一种 **/ public class Decorator_zero extends Decorator { public Decorator_zero(Human human) { super(human); } private void put(){ System.out.println("进房子"); } private void finMap(){ System.out.println("书柜找找Map"); } @Override public void wearClothes() { super.wearClothes(); put(); } @Override public void walkToWhere() { super.walkToWhere(); finMap(); } } /** *//** *这是第二种 **/ public class Decorator_first extends Decorator{ public Decorator_first(Human human) { super(human); } private void put(){ System.out.println("去衣柜找找"); } private void where(){ System.out.println("先找张地图"); } @Overrde public void wearClothes() { super.wearClothes(); put(); } @Override public void walkToWhere() { super.walkToWhere(); where(); } } /** *//** *这是第三种 **/ public class Decorator_second extends Decorator { public Decorator_second(Human human) { super(human); } private void put(){ System.out.println("找到一件D&G"); } private void where(){ System.out.println("从地图上找到神秘花园以及城堡"); } @Override public void wearClothes() { super.wearClothes(); put(); } @Override public void walkToWhere() { super.walkToWhere(); where(); }}/** *//** *定义被装饰者,该被装饰者初始状态会有一些自己的装饰 **/public class Person implements Human { public void walkToWhere() { System.out.println("去哪里呢"); } public void wearClothes() { System.out.println("穿什么呢"); }}/** *//** *测试类,下面越看越帅。。。怎一个帅字了得。。。这明显 *是java.io的层次嘛。。。哈哈 **/public class Test {public static void main(String[] args) { Human human = new Person(); Decorator dt = new Decorator_second(new Decorator_first(new Decorator_zero(human))); dt.wearClothes(); dt.walkToWhere(); }}关键点: