Several ways for a class to provide a default object in Java

Several ways for a class to provide a default object in Java

1. Static member variables (recommended)

1 Overview

Declare a static member variable in the class as an instance of the default object and initialize it to the default value. Other code can directly access this static member variable to obtain the default object.

2. Code example

public class MyClass {
    
    
    private static final MyClass DEFAULT_INSTANCE = new MyClass();

    public static MyClass getDefaultInstance() {
    
    
        return DEFAULT_INSTANCE;
    }

    // 其他类的方法和属性...
}

2. Static factory method

1 Overview

Add a static factory method to the class that returns an instance of the default object. A static factory method can internally create and return an instance of the class, setting default properties and state as needed.

2. Code example

public class MyClass {
    
    

    public static MyClass createDefaultInstance() {
    
    
        MyClass instance = new MyClass();
        // 设置默认属性和状态
        return instance;
    }

    // 其他类的方法和属性...
}

3. Constructor

1 Overview

Make the default object's constructor public and set default properties and state there. Other code can use this constructor directly to create default object instances.

2. Code example

public class MyClass {
    
    
    private String property;

    public MyClass() {
    
    
        this.property = "default value";
    }

    // 其他类的方法和属性...
}

Guess you like

Origin blog.csdn.net/qq_29689343/article/details/131500234