Java Factory Method Pattern

  1. Why using factory method pattern

Instead of calling a constructor directly, you call a creation method on a factory object which produces an implementation of the interface thus making it possible to transparently swap one implementation for another.


In theory, your code is completely isolated from the implementation of the interface.

  1. A simple example for factory method

Service <-- Implementation1 & Implementation2
ServiceFactory <-- Im1F& Im2F

 interface Service {
    void method1();
    void method2();
 }

 interface ServiceFactory {
    Service getService();
 }
 
 class Implementation1 implements Service {
     Implementation1() {}
     public void method1() { print("Implementation1 method1");}
     public void method2() { print("Implementation1 method2");}
 }

 class Implementation1Factory implements ServiceFactory {
     public Service getService() {
             return new Implementation1();
      }
  }

 class Implementation2 implements Service {
     Implementation2() {}
     public void method1() { print("Implementation2 method1");}
     public void method2() { print("Implementation2 method2");}
 }

 class Implementation2Factory implements ServiceFactory {
     public Service getService() {
             return new Implementation2();
      }
  }

 public class Factories {
    public static void serviceConsumer(ServiceFactory fact) {
        Service s = fact.getService();
        s.method1();
        s.method2();
     }
     public static void main(String[] args) {
        serviceConsumer(new Implementation1Factory());
        serviceConsumer(new Implementation2Factory());
      }
 }

 // Output:
    Implementation1 method1
    Implementation1 method2
    Implementation2 method1
    Implementation2 method2

One more easy example about this is in here.

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • **2014真題Directions:Read the following text. Choose the be...
    又是夜半驚坐起閱讀 11,271評論 0 23
  • ? 挑戰(zhàn)一 在這張圖片中你能看到幾個紅球? 5個? 6個? 經(jīng)過仔細(xì)的觀察,你最終的答案是什么? 什么?你只能看到...
    e5a2ee3bb269閱讀 290評論 0 1
  • 新學(xué)期,你的愿望是什么 ——寫給新學(xué)期的你 小魔怪教室家人: 前兩天我在朋友圈里發(fā)了一個問題,問得是:當(dāng)放假和...
    我本為旭閱讀 486評論 0 1
  • 一路走來,跌跌撞撞,能遇見最美的你,是幸運;別后三載,踉踉蹌蹌,能認(rèn)識最好的我,是成長;前路迷茫,磕磕絆絆,會擁有...
    未來藍(lán)醉閱讀 639評論 0 2
  • 你們讓我感動 文/水靈兒 為了慶祝元旦,學(xué)校讓每班準(zhǔn)備一個節(jié)目進(jìn)行演出。 為了能讓所有孩子參與表演,我決定,...
    Rrl水靈兒閱讀 576評論 0 2

友情鏈接更多精彩內(nèi)容