Java是一種非常流行的編程語言,在Java編程中,動態代理和裝飾器模式是非常關鍵的概念。下面我們分別介紹一下這兩個概念。
動態代理是一種非常普遍的編程技術,它可以在運行時為接口創建一個代理對象。在Java中,動態代理通常使用Proxy類來實現。我們可以通過反射機制來動態地創建代理對象。
public interface Subject { public void request(); } public class RealSubject implements Subject { public void request() { System.out.println("Real Subject request() method."); } } public class ProxyHandler implements InvocationHandler { private Subject subject; public ProxyHandler(Subject subject) { this.subject = subject; } public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { System.out.println("Before calling " + method.getName() + " method."); Object result = method.invoke(subject, args); System.out.println("After calling " + method.getName() + " method."); return result; } } public class Client { public static void main(String[] args) { Subject realSubject = new RealSubject(); InvocationHandler handler = new ProxyHandler(realSubject); Subject proxySubject = (Subject) Proxy.newProxyInstance(realSubject.getClass().getClassLoader(), realSubject.getClass().getInterfaces(), handler); proxySubject.request(); } } // 執行結果: // Before calling request method. // Real Subject request method. // After calling request method.
裝飾器模式是一種經典的設計模式,它允許在不改變原有對象結構的基礎上,動態地向對象添加功能。在Java中,裝飾器模式通常使用裝飾器類來實現。我們可以動態地將裝飾器對象“套在”被裝飾對象外層,從而使這個對象具有額外的功能。
public interface Component { public void operation(); } public class ConcreteComponent implements Component { public void operation() { System.out.println("Concrete Component operation() method."); } } public abstract class Decorator implements Component { private Component component; public Decorator(Component component) { this.component = component; } public void operation() { if (component != null) { component.operation(); } } } public class ConcreteDecoratorA extends Decorator { public ConcreteDecoratorA(Component component) { super(component); } public void operation() { super.operation(); addedBehavior(); } public void addedBehavior() { System.out.println("Concrete Decorator A addedBehavior() method."); } } public class ConcreteDecoratorB extends Decorator { public ConcreteDecoratorB(Component component) { super(component); } public void operation() { super.operation(); addedBehavior(); } public void addedBehavior() { System.out.println("Concrete Decorator B addedBehavior() method."); } } public class Client { public static void main(String[] args) { Component componentA = new ConcreteDecoratorA(new ConcreteComponent()); componentA.operation(); Component componentB = new ConcreteDecoratorB(new ConcreteDecoratorA(new ConcreteComponent())); componentB.operation(); } } // 執行結果: // Concrete Component operation() method. // Concrete Decorator A addedBehavior() method. Concrete Component operation() method. // Concrete Decorator B addedBehavior() method. Concrete Decorator A addedBehavior() method. Concrete Component operation() method.
以上兩個模式是Java編程中非常常用的兩種模式,它們都有自己的特點和用途,可以根據具體的情況進行使用。