本文目录导读:

我来为你详细介绍Java私有构造函数的开发案例。
基本概念
私有构造函数(Private Constructor)是指使用 private 修饰符的构造函数,只能在类内部访问。
常见使用场景
1 单例模式(Singleton Pattern)
public class Singleton {
// 私有静态实例
private static Singleton instance = null;
// 私有构造函数
private Singleton() {
System.out.println("Singleton实例被创建");
}
// 公有静态方法获取实例
public static Singleton getInstance() {
if (instance == null) {
instance = new Singleton();
}
return instance;
}
public void show() {
System.out.println("Singleton实例方法被调用");
}
}
// 测试类
public class SingletonTest {
public static void main(String[] args) {
// 错误:无法直接实例化
// Singleton s1 = new Singleton(); // 编译错误
// 正确:通过静态方法获取实例
Singleton s1 = Singleton.getInstance();
Singleton s2 = Singleton.getInstance();
System.out.println("s1 == s2: " + (s1 == s2)); // true
s1.show();
}
}
2 工具类(Utility Class)
public class MathUtils {
// 私有构造函数,防止实例化
private MathUtils() {
throw new UnsupportedOperationException("工具类不能实例化");
}
// 静态工具方法
public static int add(int a, int b) {
return a + b;
}
public static int subtract(int a, int b) {
return a - b;
}
public static int multiply(int a, int b) {
return a * b;
}
public static double divide(int a, int b) {
if (b == 0) {
throw new ArithmeticException("除数不能为0");
}
return (double) a / b;
}
}
// 测试类
public class MathUtilsTest {
public static void main(String[] args) {
// 直接使用静态方法
System.out.println("10 + 5 = " + MathUtils.add(10, 5));
System.out.println("10 - 5 = " + MathUtils.subtract(10, 5));
System.out.println("10 * 5 = " + MathUtils.multiply(10, 5));
System.out.println("10 / 5 = " + MathUtils.divide(10, 5));
// 尝试实例化会抛出异常
// new MathUtils(); // 运行时会抛出异常
}
}
3 枚举单例模式
public class EnumSingletonDemo {
// 枚举类型实现单例
public enum SingletonEnum {
INSTANCE;
private String name;
// 枚举的构造函数默认是私有的
SingletonEnum() {
this.name = "枚举单例";
}
public void show() {
System.out.println("枚举单例名称: " + name);
}
}
public static void main(String[] args) {
SingletonEnum s1 = SingletonEnum.INSTANCE;
SingletonEnum s2 = SingletonEnum.INSTANCE;
System.out.println("s1 == s2: " + (s1 == s2)); // true
s1.show();
}
}
4 工厂方法模式
public class ProductFactory {
// 私有构造函数
private ProductFactory() {}
// 内部产品类
public static class Product {
private String name;
// 私有构造函数
private Product(String name) {
this.name = name;
}
public void display() {
System.out.println("产品: " + name);
}
}
// 工厂方法
public static Product createProduct(String type) {
switch (type) {
case "A":
return new Product("产品A");
case "B":
return new Product("产品B");
default:
throw new IllegalArgumentException("未知产品类型: " + type);
}
}
}
// 测试类
public class FactoryTest {
public static void main(String[] args) {
ProductFactory.Product p1 = ProductFactory.createProduct("A");
ProductFactory.Product p2 = ProductFactory.createProduct("B");
p1.display();
p2.display();
// 无法直接创建Product实例
// new ProductFactory.Product("测试"); // 编译错误
}
}
5 构建器模式(Builder Pattern)
public class Person {
private String name;
private int age;
private String email;
// 私有构造函数
private Person(Builder builder) {
this.name = builder.name;
this.age = builder.age;
this.email = builder.email;
}
// 静态内部构建器类
public static class Builder {
private String name;
private int age;
private String email;
public Builder(String name) {
this.name = name;
}
public Builder setAge(int age) {
this.age = age;
return this;
}
public Builder setEmail(String email) {
this.email = email;
return this;
}
public Person build() {
return new Person(this);
}
}
@Override
public String toString() {
return "Person{name='" + name + "', age=" + age + ", email='" + email + "'}";
}
}
// 测试类
public class BuilderTest {
public static void main(String[] args) {
Person person = new Person.Builder("张三")
.setAge(25)
.setEmail("zhangsan@example.com")
.build();
System.out.println(person);
// 无法直接创建Person实例
// new Person(); // 编译错误
}
}
注意事项
1 私有构造函数的特点
public class PrivateConstructorDemo {
// 私有构造函数
private PrivateConstructorDemo() {
System.out.println("私有构造函数被调用");
}
// 可以在内部创建实例
private static PrivateConstructorDemo instance = new PrivateConstructorDemo();
// 内部类可以访问私有构造函数
static class Helper {
PrivateConstructorDemo demo = new PrivateConstructorDemo();
}
public static void main(String[] args) {
// 主类中可以访问自己的私有构造函数
PrivateConstructorDemo demo = new PrivateConstructorDemo();
// 内部类中可以访问
Helper helper = new Helper();
}
}
class OtherClass {
public void test() {
// 其他类无法访问私有构造函数
// PrivateConstructorDemo demo = new PrivateConstructorDemo(); // 编译错误
}
}
2 继承限制
public class ParentClass {
// 私有构造函数
private ParentClass() {
System.out.println("父类私有构造函数");
}
// 受保护的构造函数
protected ParentClass(String name) {
System.out.println("父类受保护构造函数: " + name);
}
}
// 无法继承
// class ChildClass extends ParentClass { // 编译错误
// public ChildClass() {
// super(); // 无法访问父类私有构造函数
// }
// }
// 正确做法:使用受保护的构造函数
class ChildClass extends ParentClass {
public ChildClass() {
super("子类"); // 调用父类受保护的构造函数
}
}
最佳实践
public class BestPractices {
// 1. 工具类:总是使用私有构造函数
public final class StringUtils {
private StringUtils() {
throw new AssertionError("工具类不能实例化");
}
public static boolean isEmpty(String str) {
return str == null || str.isEmpty();
}
}
// 2. 单例模式:考虑使用线程安全的方式
public class ThreadSafeSingleton {
private static volatile ThreadSafeSingleton instance;
private ThreadSafeSingleton() {}
public static ThreadSafeSingleton getInstance() {
if (instance == null) {
synchronized (ThreadSafeSingleton.class) {
if (instance == null) {
instance = new ThreadSafeSingleton();
}
}
}
return instance;
}
}
// 3. 私有构造函数配合静态工厂方法
public class Product {
private String name;
private double price;
private Product(String name) {
this.name = name;
}
private Product(String name, double price) {
this.name = name;
this.price = price;
}
// 静态工厂方法
public static Product createBasicProduct(String name) {
return new Product(name);
}
public static Product createFullProduct(String name, double price) {
return new Product(name, price);
}
}
}
这些案例展示了私有构造函数的不同使用场景和实现方式,在实际开发中能够帮助你更好地控制对象的创建过程。