Java中的工厂设计模式
欢迎使用Java教程中的Factory Design Pattern。
工厂模式是一种创新设计模式,它在JDK以及诸如Spring和Struts之类的框架中广泛使用。
工厂设计模式
当我们有一个具有多个子类的超类并且基于输入时,需要返回其中一个子类时,将使用工厂设计模式。
这种模式消除了从客户端程序到工厂类的类实例化的责任。
让我们首先学习如何在Java中实现工厂设计模式,然后再探讨工厂模式的优势。
我们将在JDK中看到一些工厂设计模式的用法。
请注意,此模式也称为工厂方法设计模式。
工厂设计模式超级类
工厂设计模式中的超级类可以是接口,抽象类或者普通的Java类。
对于我们的工厂设计模式示例,我们具有带有重写的toString()方法的抽象超类以进行测试。
package com.theitroad.design.model;
public abstract class Computer {
public abstract String get内存();
public abstract String getHDD();
public abstract String getCPU();
@Override
public String toString(){
return "内存= "+this.get内存()+", HDD="+this.getHDD()+", CPU="+this.getCPU();
}
}
工厂设计模式子类
假设我们有以下两种实现的PC和Server子类。
package com.theitroad.design.model;
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 get内存() {
return this.ram;
}
@Override
public String getHDD() {
return this.hdd;
}
@Override
public String getCPU() {
return this.cpu;
}
}
注意,这两个类都是"计算机"超级类的扩展。
package com.theitroad.design.model;
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 get内存() {
return this.ram;
}
@Override
public String getHDD() {
return this.hdd;
}
@Override
public String getCPU() {
return this.cpu;
}
}
工厂级
现在我们已经准备好超级类和子类,我们可以编写工厂类了。
这是基本的实现。
package com.theitroad.design.factory;
import com.theitroad.design.model.Computer;
import com.theitroad.design.model.PC;
import com.theitroad.design.model.Server;
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;
}
}
有关工厂设计模式方法的一些要点是:
我们可以保留Factory类的Singleton,也可以保留将子类返回为静态的方法。
请注意,基于输入参数,将创建并返回不同的子类。
getComputer是工厂方法。
这是一个使用上述工厂设计模式实现的简单测试客户端程序。
package com.theitroad.design.test;
import com.theitroad.design.factory.ComputerFactory;
import com.theitroad.design.model.Computer;
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);
}
}
上面程序的输出是:
Factory PC Config::内存= 2 GB, HDD=500 GB, CPU=2.4 GHz Factory Server Config::内存= 16 GB, HDD=1 TB, CPU=2.9 GHz
工厂设计模式的优势
工厂设计模式提供了接口代码而不是实现代码的方法。
工厂模式从客户端代码中删除了实际实现类的实例。
工厂模式使我们的代码更健壮,更少耦合且易于扩展。
例如,我们可以很容易地更改PC类的实现,因为客户端程序没有意识到这一点。工厂模式通过继承在实现和客户端类之间提供抽象。
JDK中的工厂设计模式示例
java.util.Calendar,ResourceBundle和NumberFormat
getInstance()方法使用Factory模式。包装类(例如Boolean,Integer等)中的" valueOf()"方法。

