java靜態代理

來源:互聯網
上載者:User

代理就是講 原先不相關的代碼, 在運行時 組合到一起去運行, 這樣提高程式的維護性,並讓 業務代碼 和 伺服器代碼 完全分離,以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

 

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.