————— 第二天 —————
————————————
public
interface
IStudentService
{
void
insertStudent
();
void
deleteStudent
();
}
public
class
StudentService
implements
IStudentService
{
public
void
insertStudent
(){
//新增學生
}
public
void
deleteStudent
(){
//刪除學生
}
}
public
class
StudentService
implements
IStudentService
{
public
void
insertStudent
(){
System。out。println(
“準備新增學生”
);
//新增學生
System。out。println(
“新增學生成功”
);
}
public
void
deleteStudent
(){
System。out。println(
“準備刪除學生”
);
//刪除學生
System。out。println(
“刪除學生成功”
);
}
}
public
class
StudentServiceProxy
implements
IStudentService
{
IStudentService studentService;
public
StudentServiceProxy
(IStudentService studentService){
this
。studentService = studentService;
}
@Override
public
void
insertStudent
() {
System。out。println(
“準備新增學生”
);
studentService。insertStudent();
System。out。println(
“新增學生成功”
);
}
@Override
public
void
deleteStudent
() {
System。out。println(
“準備刪除學生”
);
studentService。deleteStudent();
System。out。println(
“刪除學生成功”
);
}
}
在上面的程式碼中,代理類和業務類繼承了相同的介面,並且重寫了新增/刪除學生的方法。
在重寫的方法中,我們不僅可以呼叫業務類的原有方法,並且在呼叫的前後可以進行額外的處理,比如加上日誌、事務等等。
這樣一來,在客戶端當中,我們只要建立了代理類,就可以像使用業務類一樣使用它,非常方便:
public
class
Client
{
public
static
void
main
(String[] args) {
IStudentService studentServiceProxy =
new
StudentServiceProxy(
new
StudentService());
studentServiceProxy。insertStudent();
studentServiceProxy。deleteStudent();
}
}
以Java語言為例,Java為我們提供了十分方便的建立動態代理的工具包。當我們生成動態代理的時候,我們需要使用到
InvocationHandler
介面和
Proxy
類。
具體的實現過程如下:
1。實現InvocationHandler介面,定義呼叫方法前後所做的事情:
public
class
MyInvocationHandler
implements
InvocationHandler
{
private
Object
object;
public MyInvocationHandler(
Object
object){
this
。object = object;
}
@Override
public
Object
invoke(
Object
proxy, Method method,
Object
[] args) throws Throwable {
System。out。println(method。getName() +
“方法呼叫前”
);
method。invoke(object, args);
System。out。println(method。getName() +
“方法呼叫後”
);
return
null
;
}
}
2。透過Proxy類的newProxyInstance方法,動態生成代理物件:
public
class
Client
{
public
static
void
main(
String
[] args) {
IStudentService studentService =
new
StudentService();
InvocationHandler studentInvocationHandler =
new
MyInvocationHandler(studentService);
IStudentService studentServiceProxy = (IStudentService)
Proxy
。newProxyInstance(studentInvocationHandler。getClass()。getClassLoader(), studentService。getClass()。getInterfaces(), studentInvocationHandler);
studentServiceProxy。insertStudent();
studentServiceProxy。deleteStudent();
}
}
喜歡本文的朋友,歡迎關注公眾號
程式設計師小灰
,收看更多精彩內容