Last active
September 15, 2019 21:57
-
-
Save mtov/704348e216e85918d7375a6b3d40dcdb to your computer and use it in GitHub Desktop.
Singleton (Design Patterns)
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
class Logger { | |
private Logger() {} // proíbe clientes de chamar new Logger() | |
private static Logger instance; // instância única da classe | |
public static Logger getInstance() { | |
if(instance == null) // primeira vez que chama-se getInstance | |
instance = new Logger(); | |
return instance; | |
} | |
public void println(String msg) { | |
System.out.println(msg); // registra msg na console; mas poderia ser em arquivo também | |
} | |
} | |
public class Main { | |
void f() { | |
Logger log = Logger.getInstance(); | |
System.out.print("Log ID" + log.hashCode()); | |
log.println(" Executando f"); | |
} | |
void g() { | |
Logger log = Logger.getInstance(); | |
System.out.print("Log ID" + log.hashCode()); | |
log.println(" Executando g"); | |
} | |
void h() { | |
Logger log = Logger.getInstance(); | |
System.out.print("Log ID" + log.hashCode()); | |
log.println(" Executando h"); | |
} | |
public static void main(String [] args) { | |
Main m = new Main(); | |
System.out.println ("Veja que todos as msg de log serão enviadas o singleton (hashcode são iguais)"); | |
m.f(); | |
m.g(); | |
m.h(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment