在类的内部讲构造器私有化,创建一个static的构造方法,就是静态工厂方法替代构造器。
最简单的一个静态工厂方法替代构造器示例:(好处就是创造时更清晰)
csharp
public class Book {
private String title;
private String author;
// 私有构造函数,防止直接实例化
private Book(String title, String author) {
this.title = title;
this.author = author;
}
// 静态工厂方法
public static Book createBookByTitleAndAuthor(String title, String author) {
return new Book(title, author);
}
}
单例模式,多例模式,池化模式下,使用静态工厂方法,有一定优势:(静态工厂方法的最重要的优点)
csharp
public class Car{
private static final Map<String,Car> carPool=new HashMap<>();
private String model;
private Car(model){
this.model=model;
}
public static Car createCar(String model){
Car car=carPool.get(model);
if(car==null){
car=new Car(model);
carPool.put(model,car);
}
return car;
}
}
使用一个接口来实现静态工厂方法:
csharp
public interface Car {
void drive();
static Car createCar(String type) {
if (type.equalsIgnoreCase("Sedan")) {
return new Sedan();
} else if (type.equalsIgnoreCase("SUV")) {
return new SUV();
}
throw new IllegalArgumentException("Unknown car type");
}
class Sedan implements Car {
@Override
public void drive() {
System.out.println("Driving a Sedan");
}
}
class SUV implements Car {
@Override
public void drive() {
System.out.println("Driving an SUV");
}
}
}
public class Main {
public static void main(String[] args) {
Car sedan = Car.createCar("Sedan");
sedan.drive(); // 输出: Driving a Sedan
Car suv = Car.createCar("SUV");
suv.drive(); // 输出: Driving an SUV
}
}