静态工厂方法替代构造器

在类的内部讲构造器私有化,创建一个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
    }
}
相关推荐
麻瓜生活睁不开眼5 小时前
Android16修改全局桌面视图边框四直角显示为弧边圆角
android·java·深度学习
dear_bi_MyOnly5 小时前
【MyBatis 操作数据库】
java·数据库·学习·mybatis·学习方法
Wang's Blog5 小时前
Go-Zero 项目开发43:基于 Filebeat 收集各个服务的日志信息
开发语言·golang·go-zero·filebeat
2601_953720825 小时前
【计算机毕业设计】基于Spring Boot的心理健康咨询与评测系统的设计与实现
java·spring boot·后端
丈剑走天涯6 小时前
JDK 17 正式特性
java·开发语言
秋田君6 小时前
QT_QFontDialog类字体对话框
开发语言·qt
圣光SG6 小时前
Java操作题练习(七)
java·开发语言·算法
麻瓜老宋8 小时前
AI开发C语言应用按步走,表达式计算器calc的第二十三步,多行输入、进制输出、错误恢复、常量折叠、配置加载等
c语言·开发语言·atomcode
q567315238 小时前
企业级 HTTP 代理采购选型:技术评估清单 15 项
开发语言·网络·爬虫·网络协议·http·隧道ip·代理ip
@航空母舰8 小时前
SpringBoot通过Map实现天然的策略模式
java·spring boot·后端