Java的静态代理staticProxy

   注意事项静态代理类中的目标对象,在代理中创建,而不是外部传入的,这样的代理类就起到了保护和隐藏的作用。

   ALT+shift+M键=抽取方法

客户类

public class Client {
public static void main(String[] args) {
// 创建代理对象
ISomeService service = new ServiceProxy();
// 调用代理对象的代理方法
String someResult = service.doSome(5, "月份");
System.out.println("someResult = " + someResult);

System.out.println("=========================");

// 调用代理对象的代理方法
service.doOther();
}
}

// 目标类
public class SomeServiceImpl implements ISomeService {


// 目标方法
@Override
public String doSome(int a, String b) {
System.out.println("执行业务方法doSome()");
return a + b;
}


// 目标方法
@Override
public void doOther() {
System.out.println("执行业务方法doOther()");
}


}

// 代理类
public class ServiceProxy implements ISomeService {
private ISomeService target;
public ServiceProxy() {
target = new SomeServiceImpl();
}


// 代理方法
@Override
public String doSome(int a, String b) {
SystemUtils.doTx();
// 调用目标类的目标方法
String result = target.doSome(a, b);
SystemUtils.doLog();
return result;
}
// 代理方法
@Override
public void doOther() {
SystemUtils.doTx();
// 调用目标类的目标方法
target.doOther();
SystemUtils.doLog();
}
}

  

猜你喜欢

转载自blog.csdn.net/qq_40406929/article/details/79749288