Created
February 22, 2024 10:31
-
-
Save alexjosesilva/acb3cedebda67afefb95f0a3d53b31ff to your computer and use it in GitHub Desktop.
Singleton
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class Singleton { | |
// Instância estática privada da classe | |
private static Singleton instance; | |
// Construtor privado para evitar a criação de instâncias fora da classe | |
private Singleton() { | |
// Construtor vazio ou com inicializações necessárias | |
} | |
// Método estático público para obter a instância única da classe | |
public static Singleton getInstance() { | |
// Se a instância ainda não foi criada, cria-a | |
if (instance == null) { | |
instance = new Singleton(); | |
} | |
// Retorna a instância existente | |
return instance; | |
} | |
// Métodos da instância (opcional) | |
public void showMessage() { | |
System.out.println("Exemplo de Singleton em Java!"); | |
} | |
} | |
// Classe principal para testar o Singleton | |
public class Main { | |
public static void main(String[] args) { | |
// Obtenha a instância Singleton | |
Singleton singleton = Singleton.getInstance(); | |
// Chame um método da instância Singleton | |
singleton.showMessage(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment