工厂模式之工厂方法模式

来源:互联网 发布:thinking in java 4th 编辑:程序博客网 时间:2024/05/19 19:13
先看代码:

publicinterface Product {

   publicvoid getName();

}

publicclass AProduct implements Product{

   publicvoid getName() {

      System.out.println("I am product A");

   }

}

publicclass BProduct implements Product{

   publicvoid getName() {

      System.out.println("I am product B");

   }

}

publicinterface IFactory {

   Product createProduct();

}

publicclass AFactory implements IFactory{

   public Product createProduct() {

      returnnew AProduct();

   }

}

publicclass BFactory implements IFactory{

   public Product createProduct() {

      returnnew BProduct();

   }

}

publicclass Test {

   publicstaticvoid main(String []args){

      IFactory iFactory = new AFactory();

      Product product = iFactory.createProduct();

      product.getName();

      iFactory = new BFactory();

      product = iFactory.createProduct();

      product.getName();

   }

}

如果后来增加一类产品C,只需要增加一个C的工厂(CFactory类)和一个C产品的实现类(CProduct类),不过要修改客户端的代码,根据实际情况使用new AFactory()还是new BFactory()等等。
工厂方法模式优点:
每个工厂类对应一个对象的实现类,但需要客户端判断创建哪个工厂类实例,需求变化时,工厂类无需改变,但客户端需要修改。
简单工厂模式优点:
工厂类中包含必要的逻辑判断,客户端只需传递相应的参数便可得到想要的对象的实例化,在需求变化时,只需要修改工厂类,增加额外判断,客户端基本不用修改。











0 0
原创粉丝点击