代理模式Proxy

public class MainActivity extends AppCompatActivity {

    TextView textView;
    Button button;
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        textView = findViewById(R.id.text);
        button = findViewById(R.id.button);
        ProxySubject subject = new ProxySubject(new RealSubject());//客户端
        subject.visit();

    }
    public interface Subject {
        void visit();
    }
    public  class RealSubject implements Subject {

        private String name = "byhieg";
        @Override
        public void visit() {
            System.out.println(name);
        }
    }
    public  class ProxySubject implements Subject{

        private Subject subject;

        public ProxySubject(Subject subject) {
            this.subject = subject;
        }

        @Override
        public void visit() {
            subject.visit();
        }
    }
    }

静态代理

public class MainActivity extends AppCompatActivity {

    TextView textView;
    Button button;
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        textView = findViewById(R.id.text);
        button = findViewById(R.id.button);
        Subject realSubject = new RealSubject();
        DynamicProxy proxy = new DynamicProxy(realSubject);
        ClassLoader classLoader = realSubject.getClass().getClassLoader();
        Subject subject = (Subject) Proxy.newProxyInstance(classLoader, new  Class[]{Subject.class}, proxy);
        subject.visit();

    }
    public interface Subject {
        void visit();
    }
    public  class RealSubject implements Subject {

        private String name = "byhieg";
        @Override
        public void visit() {
            System.out.println(name);
        }
    }
    public class DynamicProxy implements InvocationHandler {
        private Object object;
        public DynamicProxy(Object object) {
            this.object = object;
        }

        @Override
        public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
            Object result = method.invoke(object, args);
            return result;
        }
    }
    }

动态代理

创建动态代理的对象,需要借助Proxy.newProxyInstance。该方法的三个参数分别是:
ClassLoader loader表示当前使用到的appClassloader。
Class<?>[] interfaces表示目标对象实现的一组接口。
InvocationHandler h表示当前的InvocationHandler实现实例对象。

转载于:https://www.cnblogs.com/Ocean123123/p/11023641.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值