首页 > 代码库 > 【设计模式】简单工厂模式和工厂方法模式
【设计模式】简单工厂模式和工厂方法模式
> 简单工厂模式
顾名思义,此模式的设计结构是简单的,核心是生产对象。
一般来说,运用工厂模式生产的对象应该是构建对象的过程比较复杂的,获取构建对象的过程在日后可能发生变更的。
简单工厂模式,在工厂类中直接生产对象,即工厂类中直接依赖对象类。
代码见:
https://github.com/nicchagil/design-pattern-exercise-with-java/tree/master/简单工厂模式
> 工厂方法模式
使用简单工厂模式,
假如有一天,Factory生产的Dog对象要全部切换为Wolf(狼),那么我们在Factory的产生方法中修改逻辑即可。(此假设场景是全部哦,既然要将产生Dog变更为产生Wolf,那么修改代码逻辑无可厚非)
假如有一天,某些客户端原来使用Cat对象的地方,需要使用Dog对象,这需要在客户端修改代码。(这也不是用工厂方法模式能解决的)
最后,假如有一天,需要添加生产一个Duck(鸭),那么难道要修改Factory?如果我们的生产方法写出如下,那么修改的代码量会更多,而且改起来容易错。
public static Animal getInstance(String type) { if (type == null || type.trim().length() == 0) { return null; } if (type.equals("dog")) { return new Dog(); } else if (type.equals("cat")) { return new Cat(); } return null; }
那么,如果,我们使用工厂方法模式,只需要增加几个类,就可完成增加Duck的类型。
实体类如“简单工厂模式”,省略。
package No002工厂方式模式;import No002工厂方式模式.model.Animal;public interface IFactory { public Animal getInstance();}
package No002工厂方式模式;import No002工厂方式模式.model.Animal;import No002工厂方式模式.model.Dog;public class DogFactory implements IFactory { public Animal getInstance() { return new Dog(); }}
package No002工厂方式模式;import No002工厂方式模式.model.Animal;import No002工厂方式模式.model.Cat;public class CatFactory implements IFactory { public Animal getInstance() { return new Cat(); }}
package No002工厂方式模式;public class Call { public static void main(String[] args) { IFactory f = new DogFactory(); System.out.println(f.getInstance()); IFactory ff = new CatFactory(); System.out.println(ff.getInstance()); }}
其类图是这样的:
【设计模式】简单工厂模式和工厂方法模式
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。