设计模式工厂模式
本文最后更新于:2024年11月10日 下午
设计模式工厂模式
-
工厂模式(Factory Pattern)是 Java 中最常用的设计模式之一。这种类型的设计模式属于创建型模式,它提供了一种创建对象的最佳方式。
-
在工厂模式中,我们在创建对象时不会对客户端暴露创建逻辑,并且是通过使用一个共同的接口来指向新创建的对象。
-
优点:
- 一个调用者想创建一个对象,只要知道其名称就可以了。
- 扩展性高,如果想增加一个产品,只要扩展一个工厂类就可以。
- 屏蔽产品的具体实现,调用者只关心产品的接口。
-
缺点:每次增加一个产品时,都需要增加一个具体类和对象实现工厂,使得系统中类的个数成倍增加,在一定程度上增加了系统的复杂度,同时也增加了系统具体类的依赖。这并不是什么好事。
-
使用场景:
- 日志记录器:记录可能记录到本地硬盘、系统事件、远程服务器等,用户可以选择记录日志到什么地方。
- 数据库访问,当用户不知道最后系统采用哪一类数据库,以及数据库可能有变化时。
- 设计一个连接服务器的框架,需要三个协议,“POP3”、“IMAP”、“HTTP”,可以把这三个作为产品类,共同实现一个接口。
应用场景
- JDK 中 Calendar 的 getInstance 方法。
- JDBC 中的 Connection 对象的获取。
- Spring 中 IoC 容器创建管理bean 对象。
- 反射中 Class 对象的 newInstance 方法。
实例
- 假设子类 PC 和 Server 实现了 Computer:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53
| public class PC extends Computer { private String ram; private String hdd; private String cpu; public PC(String ram, String hdd, String cpu){ this.ram=ram; this.hdd=hdd; this.cpu=cpu; } @Override public String getRAM() { return this.ram; } @Override public String getHDD() { return this.hdd; } @Override public String getCPU() { return this.cpu; } }
public class Server extends Computer { private String ram; private String hdd; private String cpu; public Server(String ram, String hdd, String cpu){ this.ram=ram; this.hdd=hdd; this.cpu=cpu; } @Override public String getRAM() { return this.ram; } @Override public String getHDD() { return this.hdd; } @Override public String getCPU() { return this.cpu; } }
|
1 2 3 4 5 6 7 8 9 10 11
| public class ComputerFactory { public static Computer getComputer(String type, String ram, String hdd, String cpu){ if ("PC".equalsIgnoreCase(type)) return new PC(ram, hdd, cpu); else if("Server".equalsIgnoreCase(type)) return new Server(ram, hdd, cpu); return null; } }
|
注意
- 工厂类可以是单例的,getComputer 可以是静态的;
- getComputer 是工厂类的方法,且基于相同的参数类型返回了不同的对象;

- 接下来是一个简单的测试客户端程序,它使用上面的工厂设计模式实现。
1 2 3 4 5 6 7 8 9 10
| public class TestFactory { public static void main(String[] args) { Computer pc = ComputerFactory.getComputer("pc","2 GB","500 GB","2.4 GHz"); Computer server = ComputerFactory.getComputer("server","16 GB","1 TB","2.9 GHz"); System.out.println("Factory PC Config::"+pc); System.out.println("Factory Server Config::"+server); } }
|