组成:
抽象角色:通过接口或抽象类声明真实角色实现的业务方法。
代理角色:实现抽象角色,是真实角色的代理,通过真实角色的业务逻辑方法来实现抽象方法,并可以附加自己的操作。
真实角色:实现抽象角色,定义真实角色所要实现的业务逻辑,供代理角色调用。
实例:记录日志和汽车行驶的时间
/**
* 汽车运动接口
*/
public interface Moveable {
void move()
;
}
/**
* 汽车类,实现运动的具体逻辑
*/
public class Car
implements Moveable{
@Override
public void move() {
try {
Thread.
sleep(
new Random().nextInt(
1000))
;
System.
out.println(
"汽车行驶中。。。")
;
}
catch (InterruptedException e) {
e.printStackTrace()
;
}
}
}
/**
* 代理类,记录日志
*/
public class CarLogProxy
implements Moveable{
private Moveable
m;
public CarLogProxy(Moveable m){
this.
m=m
;
}
@Override
public void move() {
System.
out.println(
"日志开始。。。")
;
m.move()
;
System.
out.println(
"日志结束。。。")
;
}
}
/**
* 代理类,记录行驶时间
*/
public class CarTimeProxy
implements Moveable{
private Moveable
m;
public CarTimeProxy(Moveable m){
super()
;
this.
m=m
;
}
@Override
public void move() {
long starttime=System.
currentTimeMillis()
;
System.
out.println(
"汽车开始行驶。。。")
;
m.move()
;
long endtime=System.
currentTimeMillis()
;
System.
out.println(
"汽车结束行驶。。。")
;
System.
out.println(
"汽车行驶时间:"+(endtime-starttime)+
"毫秒")
;
}
}
测试:
public class Client {
/**
* 测试类
*/
public static void main(String[] args){
Car car=
new Car()
;
CarTimeProxy ctp=
new CarTimeProxy(car)
;
CarLogProxy clp=
new CarLogProxy(ctp)
;
clp.move()
;
}
} 日志开始。。。
汽车开始行驶。。。
汽车行驶中。。。
汽车结束行驶。。。
汽车行驶时间:508毫秒
日志结束。。。