静态工厂方法替代构造器

在类的内部讲构造器私有化,创建一个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
    }
}
相关推荐
Cc.Y2 小时前
Java零基础入门:字符串深度掌握——从基础API到StringBuilder性能优化
java·开发语言·性能优化
java资料站6 小时前
十一、评估测试
开发语言·人工智能·python
左手の明天6 小时前
SLIP 协议封装与解析详解:原理、C 代码与实战案例
linux·c语言·开发语言·c++
shuoshuohaohao7 小时前
MyBatis 小知识点
java·spring·mybatis
海上小飞龙7 小时前
【KMP算法-下篇】同一道题:Java 库函数 2600 微秒,手写 KMP 16 微秒
java·开发语言·算法
朝朝辞暮i7 小时前
C++ 第 12 课:局部变量、作用域、变量生命周期
开发语言·c++·算法
狗凯之家源码网7 小时前
淘客口令落地页生成器 PHP 版深度评测
开发语言·php
画绛集美术7 小时前
本地化部署LLM用于美术史问答:一间美术教室的实践记录
开发语言·php
谢亮_vipxieliang8 小时前
泛型擦除、通配符与 PECS 一次讲透
java·面试
八解毒剂8 小时前
【计组】中央处理器CPU
java·开发语言·计算机组成原理