静态代理是一种编译期增强,还没运行就已经知道增强的目标对象。
装饰者是运行时增强,只有运行时才知道具体增强的目标。
- Code show time
静态代理:
package com.zjt.test; interface Duck { void swim(); } class DuckImpl implements Duck{ @Override public void swim() { System.out.println("小鸭子会游泳"); } } class ProxyDuck implements Duck{ Duck duck; //一个空的构造函数,且代理类中明确声明需要代理的目标对象 public ProxyDuck(){ this.duck=new DuckImpl(); } @Override public void swim() { System.out.println("噶嘎嘎。。。"); duck.swim(); } } class Test{ public static void main(String[] args) { Duck duck = new ProxyDuck(); duck.swim(); } }
装饰者模式:
package com.zjt.test; public interface Duck { void swim(); } class DuckImpl implements Duck{ @Override public void swim() { System.out.println("swim...."); } } class Director implements Duck{ Duck duck; //编译期不知道具体的目标对象,只有运行期调用者手动传入才知道 public Director(Duck duck){ this.duck=duck; } @Override public void swim() { System.out.println("gagaga.....1"); duck.swim(); System.out.println("gagaga.....2"); } } class Test{ public static void main(String[] args) { Duck duck = new Director(new DuckImpl()); duck.swim(); } }
原文地址:https://www.cnblogs.com/zjting/p/12547092.html
时间: 2024-11-09 00:12:30