需求:設(shè)計(jì)一個(gè)車類芥驳,具有方法run,現(xiàn)需要設(shè)計(jì)一個(gè)方案計(jì)算它的前后行駛時(shí)間谭期。
一般來說該類可以這樣寫
public class car{
long start,end;
private void before(){
start=System.currentTimeMillis();
System.out.println("開車前時(shí)間:"+start);
}
private void after(){
end=System.currentTimeMillis();
System.out.println("開車后時(shí)間:"+end+".\n總耗時(shí):"+(end-start)+"毫秒");
}
pubic void run(){
try {
after();
System.out.println("正在開車~~~");
Thread.sleep((int)(Math.random()*100));
before();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
- 結(jié)果為:
開車前時(shí)間:1503127134747
正在開車~~~
開車后時(shí)間:1503127135124.
總耗時(shí):377毫秒
Process finished with exit code 0
但是為了可以擴(kuò)展堵第,一般采取寫法
Icar.java (汽車接口)
package cn.niriqiang.demo;
/**
* Created by fengyuwusong on 2017/8/19 14:53.
*/
public interface ICar {
public void run();
}
CarImpl 汽車實(shí)現(xiàn)類
package cn.niriqiang.demo;
/**
* Created by fengyuwusong on 2017/8/19 14:54.
*/
public class CarImpl implements ICar{
@Override
public void run() {
try {
System.out.println("正在開車~~~");
Thread.sleep((int)(Math.random()*1000));
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
CarProxy 汽車計(jì)時(shí)功能代理
package cn.niriqiang.demo;
/**
* Created by fengyuwusong on 2017/8/19 14:58.
*/
public class Carproxy implements ICar{
private ICar car;
long start,end;
public Carproxy(ICar car) {
this.car = car;
}
@Override
public void run() {
before();
car.run();
after();
}
private void before(){
start=System.currentTimeMillis();
System.out.println("開車前時(shí)間:"+start);
}
private void after(){
end=System.currentTimeMillis();
System.out.println("開車后時(shí)間:"+end+".\n總耗時(shí):"+(end-start)+"毫秒");
}
}
main 測(cè)試方法
package cn.niriqiang.demo;
/**
* Created by fengyuwusong on 2017/8/19 14:55.
*/
public class main {
public static void main(String[] args) {
ICar car=new CarImpl();
Carproxy carproxy=new Carproxy(car);
carproxy.run();
}
}
以上寫法即為代理模式的靜態(tài)代理,這樣的好處是加入需求改變隧出,需要在汽車行駛前后添加新功能時(shí)踏志,我們可以根據(jù)功能給汽車添加新的代理,例如:
CarLogProxy.java 給汽車添加日志功能
package cn.niriqiang.demo;
/**
* Created by fengyuwusong on 2017/8/19 15:27.
*/
public class CarLogProxy implements ICar{
ICar car;
public CarLogProxy(ICar car) {
this.car = car;
}
private void before(){
System.out.println("開車前日志:xxxxx...");
}
private void after(){
System.out.println("開車后日志:xxxxx...");
}
@Override
public void run() {
before();
car.run();
after();
}
}
我們給man方法稍作改變即可得到新功能(既添加了計(jì)時(shí)又添加了日志功能的汽車)
package cn.niriqiang.demo;
/**
* Created by fengyuwusong on 2017/8/19 14:55.
*/
public class main {
public static void main(String[] args) {
ICar car=new CarImpl();
Carproxy carproxy=new Carproxy(car);
CarLogProxy carLogProxy=new CarLogProxy(carproxy);
carLogProxy.run();
}
}
結(jié)果
開車前日志:xxxxx...
開車前時(shí)間:1503127842768
正在開車~~~
開車后時(shí)間:1503127842835.
總耗時(shí):67毫秒
開車后日志:xxxxx...