前言:

  代理模式作为常见的设计模式之一,在项目开发中不可或缺。本文就尝试着揭开代理的神秘面纱,也欢迎各路人批评指正!

1.如何实现代理:

【假设有个关于汽车移动(move)的计时需求】
设计:Moveable接口,一个Car的实现类;两个代理CarTimer,TimeHandler.UML图如下:

神秘代理-Proxy
1)继承

 1 package com.gdufe.proxy;
 2 
 3 import java.util.Random;
 4 
 5 public class CarTimer extends Car {
 6     
 7     @Override
 8     public void move() {
 9         long start=System.currentTimeMillis();
10         super.move();        //调用父类的move()方法
11         try{
12             Thread.sleep(new Random().nextInt(10000));
13         }catch(Exception e){
14             e.printStackTrace();
15         }
16         long end=System.currentTimeMillis();
17         System.out.println("I'm time machine.Time for moving:"+(end-start));
18     }
19 }
View Code

相关文章:

  • 2021-04-26
  • 2021-08-06
  • 2021-08-16
  • 2022-02-12
  • 2021-09-07
  • 2021-08-28
  • 2021-08-03
  • 2022-12-23
猜你喜欢
  • 2021-06-07
  • 2021-10-03
  • 2022-12-23
  • 2021-10-31
  • 2022-12-23
  • 2021-12-04
  • 2021-12-23
相关资源
相似解决方案