public interface Behavior { void perform(); } public class Implementation implements Behavior { public void perform() { System.out.println("Original behavior"); } } public class AdjustableBehaviorHandler implements InvocationHandler { private Behavior targetBehavior; public AdjustableBehaviorHandler(Behavior behavior) { this.targetBehavior = behavior; } public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { System.out.println("Before method"); Object result = method.invoke(targetBehavior, args); System.out.println("After method"); return result; } } public class AdjustableBehaviorFactory { public static Behavior createAdjustableBehavior() { Behavior behavior = new Implementation(); AdjustableBehaviorHandler handler = new AdjustableBehaviorHandler(behavior); Behavior proxy = (Behavior) Proxy.newProxyInstance( behavior.getClass().getClassLoader(), behavior.getClass().getInterfaces(), handler); return proxy; } } public class Main { public static void main(String[] args) { Behavior behavior = AdjustableBehaviorFactory.createAdjustableBehavior(); behavior.perform(); } }


上一篇:
下一篇:
切换中文