Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- public class SingletonTest {
- public static void main(String[] args) {
- FirstSingleton.INSTANCE.hello();
- //output: Hello the first singleton!
- SecondSingleton.getInstance().hello();
- //output: Hello the second singleton!
- ThirdSingleton.INSTANCE.hello();
- //output: Hello the third singleton!
- }
- }
- class FirstSingleton {
- public static final FirstSingleton INSTANCE = new FirstSingleton();
- private FirstSingleton() {
- //защита от рефлексии
- if (INSTANCE != null) {
- throw new InstanceAlreadyExistException();
- }
- }
- public void hello() {
- System.out.println("Hello the first singleton!");
- }
- }
- class SecondSingleton {
- private static final SecondSingleton INSTANCE = new SecondSingleton();
- public static SecondSingleton getInstance() {
- return INSTANCE;
- }
- private SecondSingleton() {
- //защита от рефлексии
- if (INSTANCE != null) {
- throw new InstanceAlreadyExistException();
- }
- }
- public void hello() {
- System.out.println("Hello the second singleton!");
- }
- }
- enum ThirdSingleton {
- INSTANCE;
- public void hello() {
- System.out.println("Hello the third singleton!");
- }
- }
- class InstanceAlreadyExistException extends RuntimeException {
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement