设计模式:JDK静态代理之Thread/Runnable

静态代理有如下要素:

1.目标角色(真实角色)。

2.代理角色。

3.目标角色和代理角色实现同一接口。

4.代理角色持有目标角色的引用。

下面的例子是一个简单的静态代理模式。

统一接口:

package com.xs.pattern.staticproxy;

/**
 * 统一接口
 * 
 * @author Administrator
 * 
 */
public interface Callable {
	void call();
}

目标角色:

package com.xs.pattern.staticproxy;

/**
 * 目标角色
 * 
 * @author Administrator
 * 
 */
public class Target implements Callable {

	public void call() {
		System.out.println("call...");
	}

}
代理角色:
package com.xs.pattern.staticproxy;

/**
 * 代理角色
 * 
 * @author Administrator
 * 
 */
public class Proxy implements Callable {

	Callable callable;

	public Proxy(Callable callable) {
		this.callable = callable;
	}

	public void call() {
		System.out.println("before...");
		callable.call();
		System.out.println("after...");
	}

}
测试:
package com.xs.pattern.staticproxy;

public class StaticProxyApp {
	public static void main(String[] args) {
		Callable target = new Target();
		Callable proxy = new Proxy(target);
		proxy.call();
	}
}
输出:
before...
call...
after...


JDK中最典型的静态代理就是线程的使用了。

package com.xs.pattern.staticproxy;

public class ThreadStaticProxy {
	public static void main(String[] args) {
		Runnable target = new MyTarget();// 目标角色
		Thread proxy = new Thread(target);// 代理角色
		proxy.start();
	}
}

class MyTarget implements Runnable {

	public void run() {
		System.out.println("run...");
	}
}

线程体(也就是我们要执行的具体任务)实现了Runnable接口和run方法。同时Thread类也实现了Runnable接口。此时,线程体就相当于目标角色,Thread就相当于代理角色。当程序调用了Thread的start()方法后,Thread的run()方法会在某个特定的时候被调用。thread.run()方法:

    public void run() {
	if (target != null) {
	    target.run();
	}
    }
实际上是执行了线程体的代码。




  • 4
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值