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

静态代理有如下要素:

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

2.代理角色。

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

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

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

统一接口:

  1. package com.xs.pattern.staticproxy;  
  2.   
  3. /** 
  4.  * 统一接口 
  5.  *  
  6.  * @author Administrator 
  7.  *  
  8.  */  
  9. public interface Callable {  
  10.     void call();  
  11. }  

目标角色:

  1. package com.xs.pattern.staticproxy;  
  2.   
  3. /** 
  4.  * 目标角色 
  5.  *  
  6.  * @author Administrator 
  7.  *  
  8.  */  
  9. public class Target implements Callable {  
  10.   
  11.     public void call() {  
  12.         System.out.println("call...");  
  13.     }  
  14.   
  15. }  
代理角色:
  1. package com.xs.pattern.staticproxy;  
  2.   
  3. /** 
  4.  * 代理角色 
  5.  *  
  6.  * @author Administrator 
  7.  *  
  8.  */  
  9. public class Proxy implements Callable {  
  10.   
  11.     Callable callable;  
  12.   
  13.     public Proxy(Callable callable) {  
  14.         this.callable = callable;  
  15.     }  
  16.   
  17.     public void call() {  
  18.         System.out.println("before...");  
  19.         callable.call();  
  20.         System.out.println("after...");  
  21.     }  
  22.   
  23. }  
测试:
  1. package com.xs.pattern.staticproxy;  
  2.   
  3. public class StaticProxyApp {  
  4.     public static void main(String[] args) {  
  5.         Callable target = new Target();  
  6.         Callable proxy = new Proxy(target);  
  7.         proxy.call();  
  8.     }  
  9. }  
输出:
  1. before...  
  2. call...  
  3. after...  


JDK中最典型的静态代理就是线程的使用了。
  1. package com.xs.pattern.staticproxy;  
  2.   
  3. public class ThreadStaticProxy {  
  4.     public static void main(String[] args) {  
  5.         Runnable target = new MyTarget();// 目标角色  
  6.         Thread proxy = new Thread(target);// 代理角色  
  7.         proxy.start();  
  8.     }  
  9. }  
  10.   
  11. class MyTarget implements Runnable {  
  12.   
  13.     public void run() {  
  14.         System.out.println("run...");  
  15.     }  
  16. }  

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

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



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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值