代理就是講 原先不相關的代碼, 在運行時 組合到一起去運行, 這樣提高程式的維護性,並讓 業務代碼 和 伺服器代碼 完全分離,以Person為例. --下篇在寫動態代理, AOP..
Person 介面:
public
interface
IPerson {
public void sleep();
public void walk();
}
Person 實作類別:
public
class PersonImp implements
IPerson{
public
void sleep() {
System.out
.println("sleep..."); //業務代碼 ,比如 往資料庫插入資料, 但不包括 事務
}
public
void walk() {
System.out
.println("walk..."); //業務代碼
,比如 往資料庫插入資料, 但不包括 事務
}
}
Person代理類, 實現IPerson介面:
public
class ProxyPerson implements
IPerson{
private
IPerson person;
public
void setPerson(IPerson person) {
this.person = person;
}
public
ProxyPerson(IPerson person) {
super
();
this.person = person;
}
public
void sleep() {
System.out
.println("befor sleep"); //服務代碼, 比如事務的開啟
person.sleep(); //調用 PersonImp 的 sleep方法
System.out
.println("after sleep"); //服務代碼, 比如事務的提交,和復原
}
public
void walk() {
System.out
.println("befor walk"); //服務代碼, 比如事務的開啟
person.walk(); //調用 PersonImp 的 walk方法
System.out
.println("after walk"); //服務代碼, 比如事務的提交,和復原
}
}
測試:
public
class StaticProxyTest {
public
static
void main(String[] args) {
IPerson person = new ProxyPerson(new PersonImp()); //由於ProxyPerson 和 PersonImp 都實現了IPerson介面,所以可以用IPerson接收,然後調用起方法
person.sleep(); // 實際上是調用的 ProxyPerson 裡面的 sleep方法
person.walk(); // 實際上是調用的 ProxyPerson 裡面的 sleep方法
}
}
效果:
befor sleep
sleep...
after sleep
befor walk
walk...
after walk