美文网首页
代理模式

代理模式

作者: 起嚸_ | 来源:发表于2019-02-21 20:38 被阅读0次
    public interface Image {
       void display();
    }
    
    public class RealImage implements Image {
    
       private String fileName;
    
       public RealImage(String fileName){
          this.fileName = fileName;
          loadFromDisk(fileName);
       }
    
       @Override
       public void display() {
          System.out.println("Displaying " + fileName);
       }
    
       private void loadFromDisk(String fileName){
    //第一次新建时执行
          System.out.println("Loading " + fileName);
       }
    }
    
    public class ProxyImage implements Image{
    
       private RealImage realImage;
       private String fileName;
    
       public ProxyImage(String fileName){
          this.fileName = fileName;
       }
    
       @Override
       public void display() {
          if(realImage == null){
             realImage = new RealImage(fileName);
          }
          realImage.display();
       }
    }
    

    动态代理

        public interface Person {
            void giveMoney();
        }
    
        public class Student implements Person {
            public Student() {
            }
    
            @Override
            public void giveMoney() {
                System.out.println ("上交班费50元");
            }
        }
    
        public class StuInvocationHandler<T> implements InvocationHandler {
            T target;
    
            public StuInvocationHandler(T target) {
                this.target = target;
            }
            
            @Override
            public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                System.out.println("代理执行" +method.getName() + "方法");
                Object result = method.invoke(target, args);
                return result;
            }
        }
    
            Person zhangsan = new Student();
    
            //创建一个与代理对象相关联的InvocationHandler
            InvocationHandler stuHandler = new StuInvocationHandler<Person>(zhangsan);
            //创建一个代理对象stuProxy来代理zhangsan,代理对象的每个执行方法都会替换执行Invocation中的invoke方法
            Person stuProxy = (Person) Proxy.newProxyInstance(Person.class.getClassLoader(), new Class<?>[]{Person.class}, stuHandler);
            stuProxy.giveMoney();
    

    相关文章

      网友评论

          本文标题:代理模式

          本文链接:https://www.haomeiwen.com/subject/qbanfftx.html