Advertisement
Guest User

Untitled

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