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.

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • **2014真题Directions:Read the following text. Choose the be...
    又是夜半惊坐起阅读 13,482评论 0 23
  • ​ 挑战一 在这张图片中你能看到几个红球? 5个? 6个? 经过仔细的观察,你最终的答案是什么? 什么?你只能看到...
    e5a2ee3bb269阅读 1,755评论 0 1
  • 新学期,你的愿望是什么 ——写给新学期的你 小魔怪教室家人: 前两天我在朋友圈里发了一个问题,问得是:当放假和...
    我本为旭阅读 3,211评论 0 1
  • 一路走来,跌跌撞撞,能遇见最美的你,是幸运;别后三载,踉踉跄跄,能认识最好的我,是成长;前路迷茫,磕磕绊绊,会拥有...
    未来蓝醉阅读 3,660评论 0 2
  • 你们让我感动 文/水灵儿 为了庆祝元旦,学校让每班准备一个节目进行演出。 为了能让所有孩子参与表演,我决定,...
    Rrl水灵儿阅读 3,434评论 0 2