개인공부/language

[JAVA] Effective JAVA - Item 3 : Enforce the singleton property with a privateconstructor or an enum type

파뱁 2025. 3. 24. 20:55
728x90

what is 'Singleton'?

 

A class that is instantiated exactly once

Singletons typically represent either a stateless object such as a function or system component that is intrinsically unique.

 

The limit of singletons

- Making a class a singleton can make it difficult to test its clients

 

There are two common ways to implement singletons

(Both are based on keeping the constructor private and exporting a public static member to provide access to the sole instance)

 

1. Member is a final field

// Singleton with public final field
public class Elvis {
	public static final Elvis INSTANCE = new Elvis();
	private Elvis() { ... }
	public void leaveTheBuilding() { ... }
}

 

The private constructor is called only once, to initialize the public static final field Elvis.INSTANCE.

 

- Pros

   - API makes it clear that the class is a singleton

   - It's simpler

 

 

2. The public member is a static factory method

// Singleton with static factory
public class Elvis {
    private static final Elvis INSTANCE = new Elvis();
    private Elvis() { ... }
    public static Elvis getInstance() { return INSTANCE; }
    public void leaveTheBuilding() { ... }
}

 

- Pros

  - It gives you the flexibility to change your mind about whether the class is a singleton without changing its API

  - You can write a generic singleton factory if your application requires it

  - Method reference can be used as a supplier*

     (*supplier : Interface that can return any kind of type with get() )

 

3. Single-element enum type is often the best way to implement a singleton

 

public enum Elvis {
	INSTANCE; 
	
	public String getName() {
		return "Elvis";
	}

	public void leaveTheBuilding() { ... }
}
String name = Elvis.INSTANCE.getName();

 

But, If you make the singlr ton that have to extend other super class, you can't use this.

728x90
반응형