從頭認識java-7.8 介面與原廠模式

來源:互聯網
上載者:User

從頭認識java-7.8 介面與原廠模式

這一章節我們來聊聊介面與原廠模式之間的關係。

介面是實現多重繼承的途徑,產生遵循某個介面協議的對象的典型方式是工廠設計模式。

這種設計模式使得介面與實現完全分開。

package com.ray.ch07;interface Service {void doSomeThing();}interface ServiceFactory {Service getService();}class ServiceImpl implements Service {@Overridepublic void doSomeThing() {}}class ServiceFactoryImpl implements ServiceFactory {@Overridepublic Service getService() {// TODO Auto-generated method stubreturn null;}}public class Test {public static void test(ServiceFactory factory) {Service service = factory.getService();service.doSomeThing();}public static void main(String[] args) {test(new ServiceFactoryImpl());}}


從上面的代碼看出,我們只是在最後一步new的時候,才把實作類別放進去,其他的代碼基本以介面來實現,從而把介面與實現完全分離,這樣有利於Test這個代碼的重複使用。

那麼,怎麼使用呢?

我們下面給出例子:(就是有多個Service的時候,Test就可以重複使用了)

package com.ray.ch07;interface Service {void doSomeThing();}interface ServiceFactory {Service getService();}class ServiceImpl implements Service {@Overridepublic void doSomeThing() {}}class ServiceFactoryImpl implements ServiceFactory {@Overridepublic Service getService() {// TODO Auto-generated method stubreturn null;}}class ServiceImpl2 implements Service {@Overridepublic void doSomeThing() {}}class ServiceFactoryImpl2 implements ServiceFactory {@Overridepublic Service getService() {// TODO Auto-generated method stubreturn null;}}public class Test {public static void test(ServiceFactory factory) {Service service = factory.getService();service.doSomeThing();}public static void main(String[] args) {test(new ServiceFactoryImpl());test(new ServiceFactoryImpl2());}}


當我們有n個Service的實作類別時,我們只需要寫一份Test代碼,然後根據實際情況new不同的實作類別,這樣就可以重複使用Test的代碼來測試。

 

最後,原廠模式這些設計模式還有其他很多的應用,我們將在另外的一個課程裡面討論,這裡不再做詳細展開。

 

總結:這一章節主要討論了介面與設計模式之間的關係。

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.