源码中的设计模式-静态代理模式
这种模式可以实现,被代理类将前期准备和后期善后的工作交给代理类实现,而核心业务由被代理类执行。其实我们经常遇到或者使用这种设计模式,常见到意识不到它用到了设计模式。
我们在使用线程的时候,经常会定义自己的线程类MyThread实现Runnable接口,在run方法中实现自己要执行的关键业务。伪代码如下:
public class ThreadTest{
public static void main(String[] args) {
Thread thread = new Thread(new MyRunnable());//静态代理模式 Thread类也实现了Runnable接口
thread.start();
}
}
class MyRunnable implements Runnable {
@Override
public void run() {
// 业务代码
System.out.println("子线程ID:" + Thread.currentThread().getId());
}
}
其中Thread类也实现了Runnable接口
public
class Thread implements Runnable {
...
private Runnable target;
...
public Thread(Runnable target) {
init(null, target, "Thread-" + nextThreadNum(), 0);
}
...
@Override public void run() {
if (target != null)
{ target.run(); }
} ...
}
可以看到静态代理设计模式涉及到,代理类、被代理类、公共接口三个关键元素。代理类和被代理类都要实现公共接口,同时代理类中须要有一个被代理类的依赖target,这样才能把核心业务逻辑交还给被代理类,而代理类只需要实现其他与核心业务逻辑无关的内容。
收住自己的心 一步一个脚印 做好自己的事

浙公网安备 33010602011771号