代理模式Proxy
?
class="java" name="code">/** * 抽象主题角色 * @author InJavaWeTrust */ public abstract class Emperor { public abstract void say(); }
?
/** * 真实主题角色 * @author InJavaWeTrust */ public class EmperorLingofHan extends Emperor { private String decree = "曹阿瞒是汉賊"; public EmperorLingofHan(String decree) { this.decree = decree; } @Override public void say() { System.out.println(this.decree); } }
?
/** * 代理主题角色 * @author InJavaWeTrust */ public class TraitorCao extends Emperor { private String decree = "曹操匡扶汉室"; private EmperorLingofHan emperor; public TraitorCao() { } @Override public void say() { preRequest(); if (emperor == null) { emperor = new EmperorLingofHan(this.decree); } emperor.say(); afterRequest(); } private void preRequest() { } private void afterRequest() { } }
?
/** * 测试类 * @author InJavaWeTrust */ public class TestProxy { public static void main(String[] args) { Emperor emperor = new TraitorCao(); emperor.say(); } }
?