Advertisement
Guest User

Untitled

a guest
Sep 20th, 2019
100
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.40 KB | None | 0 0
  1. public class SingletonTest {
  2. public static void main(String[] args) {
  3. FirstSingleton.INSTANCE.hello();
  4. //output: Hello the first singleton!
  5.  
  6. SecondSingleton.getInstance().hello();
  7. //output: Hello the second singleton!
  8.  
  9. ThirdSingleton.INSTANCE.hello();
  10. //output: Hello the third singleton!
  11. }
  12. }
  13.  
  14. class FirstSingleton {
  15. public static final FirstSingleton INSTANCE = new FirstSingleton();
  16.  
  17. private FirstSingleton() {
  18. //защита от рефлексии
  19. if (INSTANCE != null) {
  20. throw new InstanceAlreadyExistException();
  21. }
  22. }
  23.  
  24. public void hello() {
  25. System.out.println("Hello the first singleton!");
  26. }
  27. }
  28.  
  29. class SecondSingleton {
  30. private static final SecondSingleton INSTANCE = new SecondSingleton();
  31.  
  32. public static SecondSingleton getInstance() {
  33. return INSTANCE;
  34. }
  35.  
  36. private SecondSingleton() {
  37. //защита от рефлексии
  38. if (INSTANCE != null) {
  39. throw new InstanceAlreadyExistException();
  40. }
  41. }
  42.  
  43. public void hello() {
  44. System.out.println("Hello the second singleton!");
  45. }
  46. }
  47.  
  48. enum ThirdSingleton {
  49. INSTANCE;
  50.  
  51. public void hello() {
  52. System.out.println("Hello the third singleton!");
  53. }
  54. }
  55.  
  56. class InstanceAlreadyExistException extends RuntimeException {
  57.  
  58. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement