🔥码云GVP开源项目 12k star Uniapp+ElementUI 功能强大 支持多语言、二开方便! 广告
# 工厂模式 [TOC] ## 什么是工厂模式 >[info] 工厂模式,顾名思义就是类比工厂,用于生产的意思。在Java中这样的一个工厂它生产的产品是对象。 ## 工厂模式的特点 1. 工厂模式用于隐藏创建对象的细节; 2. 工厂模式核心:工厂类(Fcatory); 3. 工厂模式可细分为简单工厂、工厂方法与抽象工厂; 工厂模式主要是通过一个“中间人”来简化对象创建的过程,这个中间人就是工厂类,工厂类可根据使用行为细分为简单工厂、工厂方法和抽象工厂,其目的都是为了隐藏创建类的细节,但设计理念有所不同。 ## 工厂模式的实现 **简单工厂模式** ~~~ public interface Product { public void desc(); } public class MobilePhone implements Product { @Override public void desc() { System.out.println("生产手机"); } } public class Pad implements Product { @Override public void desc() { System.out.println("生产平板"); } } public class Computer implements Product { @Override public void desc() { System.out.println("生产电脑"); } } public class Factory { public static Product produce(String pName) { if("phone".equals(pName)) { return new MobilePhone(); } else if("computer".equals(pName)) { return new Computer(); } else if("pad".equals(pName)) { return new Pad(); } else { return null; } } } public class Demo { public static void main(String[] args) { Product pdt = Factory.produce("pad"); pdt.desc(); } } ~~~ **工厂模式** 工厂方法模式,是对普通工厂方法模式的改进,在普通工厂方法模式中,如果传递的字符串出错,则不能正确创建对象,而多个工厂方法模式是提供多个工厂方法,分别创建对象 ~~~ public interface Product { public void desc(); } public class MobilePhone implements Product { @Override public void desc() { System.out.println("生产手机"); } } public class Pad implements Product { @Override public void desc() { System.out.println("生产平板"); } } public class Computer implements Product { @Override public void desc() { System.out.println("生产电脑"); } } public class Factory { //手机生产线 public static Product mobilePhone() { return new MobilePhone(); } //电脑生产线 public static Product computer() { return new Computer(); } //平板生产线 public static Product pad() { return new Pad(); } } public class Demo { public static void main(String[] args) { Product pdt = Factory.computer(); pdt.desc(); } } ~~~ **抽象工厂模式** 自学完成