【CODE】Decoration Pattern中动态选择装饰方案

package pac.testin;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

interface Person {
    void showCommonAbility();
}

class Man implements Person {
    private String name;

    public Man(String name) {
        super();
        this.name = name;
    }

    public void showCommonAbility() {
        System.out.println("My name is " + this.name
                + "!!I can do everything you can!!");
    }

}

interface AbilityDecorator {
    void decorate();
}

class Ability_SolidSkin implements AbilityDecorator {

    public void decorate() {
        System.out.println("[Solid Skin]");
    }

}

class Ability_LightSpeed implements AbilityDecorator {

    public void decorate() {
        System.out.println("[Light Speed]");
    }
}

class Fighter implements Person {
    public Fighter(Person person, Class<? extends AbilityDecorator> ability) {
        super();
        this.person = person;
        this.ability = ability;
    }

    private Person person;
    private Class<? extends AbilityDecorator> ability;

    public void showCommonAbility() {
        InvocationHandler handler = new InvocationHandler() {

            public Object invoke(Object proxy, Method method, Object[] args)
                    throws Throwable {
                System.out.print("Research Complete:");
                method.invoke(ability.newInstance(), args);
                person.showCommonAbility();
                return null;
            }
        };
        AbilityDecorator fighter = (AbilityDecorator) Proxy.newProxyInstance(
                getClass().getClassLoader(), ability.getInterfaces(), handler);
        fighter.decorate();
    }

}

public class DynamicDecorator {
    public static void main(String[] args) {
        Person introspector = new Man("King.");
        introspector = new Fighter(introspector, Ability_SolidSkin.class);
        introspector = new Fighter(introspector, Ability_LightSpeed.class);
        introspector.showCommonAbility();
    }
}

 

posted @ 2013-03-26 19:23  Introspector  阅读(162)  评论(0编辑  收藏  举报