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.

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容