静态代理模式是指,一个类不关心其他方法的实现,只专心于自己的功能,而通过另一个代理类来调用使用它的过程。这样做可以提升效率,划分功能,各司其职。
import java.text.SimpleDateFormat;
import java.util.Date;
public class StaticProxy {
public static void main(String[] args) {
ProxyClass proxyClass = new ProxyClass(new RealClass());
proxyClass.commonMethod();
}
}
// 接口,静态代理类都要实现该接口
interface CommonInterface{
void commonMethod();
}
// 真实类
class RealClass implements CommonInterface{
@Override
public void commonMethod() {
System.out.println("RealClass");
}
}
// 代理类,代理类会比真实类有更多的操作,比如,它会告诉你当前的时间
class ProxyClass implements CommonInterface {
private CommonInterface commonInterface;
public ProxyClass(CommonInterface commonInterface) {
this.commonInterface = commonInterface;
}
@Override
public void commonMethod() {
System.out.println("ProxyClass Here");
this.commonInterface.commonMethod();
NowDate();
}
private void NowDate() {
Date date = new Date();
System.out.println("我会告诉你当前时间:" + new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(date));
}
}
- Proxy类与Real类要实现同一个接口
- 使用时不直接调用Real类,而是通过Proxy类来调用。
- Real类只需做好自己的功能;或者Real类可能是别人写的代码,为了不更改Real的代码,而使用静态代理模式