静态工厂方法替代构造器

在类的内部讲构造器私有化,创建一个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
    }
}
相关推荐
NE_STOP14 小时前
Vide Coding--AI编程工具的选择
java
LDR00615 小时前
Type-C 快充全面升级!LDR6601 赋能个人护理便携电机,重塑剃须刀 / 理发器新体验
c语言·开发语言
雪碧聊技术15 小时前
Tree.js是什么?一文讲透
开发语言·javascript·ecmascript
码云数智-园园15 小时前
C++20 Modules 模块详解
java·开发语言·spring
程序员黑豆15 小时前
JDK 下载安装与配置详细教程
java·前端·ai编程
小宇宙Zz15 小时前
Maven依赖冲突
java·服务器·maven
swordbob15 小时前
NIO的channel中什么是 fd(File Descriptor,文件描述符)
java·开发语言·nio
咖啡八杯16 小时前
GoF设计模式——享元模式
java·spring·设计模式·享元模式
十五喵源码网16 小时前
基于springboot2+vue2的租房管理系统
java·毕业设计·springboot·论文笔记
摇滚侠16 小时前
IDEA 创建 Java 项目 手动整合 SSM 框架
java·ide·intellij-idea