23种设计模式-代理模式

来源:互联网 发布:简笔画制作软件 编辑:程序博客网 时间:2024/05/16 17:21

[java] view plain copy

//接口定义    public interface MessageHandler {    public void sendMessage(String msg);    }    //通过Email方式发送消息的实现类    public class EmailMessage implements MessageHandler {    @Override    public void sendMessage(String msg) {    // TODO Auto-generated method stub    System.out.println(msg+" send!!");    }    }    //消息处理的代理类    public class MessageProxy implements MessageHandler {    private static int count;    private MessageHandler emailMsg;    @Override    public void sendMessage(String msg) {    // TODO Auto-generated method stub    if(checkMessage(msg))    {    if(emailMsg==null) emailMsg=new EmailMessage();    count++;    emailMsg.sendMessage(msg);    System.out.println("Message sent:"+count);    }    }    private boolean checkMessage(String msg) {    return msg != null && msg.length() > 10;    }    }    //调用类    public class MainClass {    private static void runProxy(MessageHandler handler)    {    handler.sendMessage("message for test");    }    /**   * @param args   */    public static void main(String[] args) {    // TODO Auto-generated method stub    runProxy(new EmailMessage());    System.out.println("++++++++++++++++Pjroxy++++++++++++++++++");    runProxy(new MessageProxy());    }    }    输出    message for test send!!    ++++++++++++++++Pjroxy++++++++++++++++++    message for test send!!    Message sent:1    

代理模式指,使用这个类时不直接去调用它,而是通过一个中间代理去调用

0 0
原创粉丝点击