Всем привет! Сегодня поговорим о самом известном шаблоне проектирования "Одиночка" (Singleton). О нем уже очень много сказано, но тем не менее - это самый популярный вопрос на собеседованиях.
Singleton - паттерн гарантирует, что класс имеет только один экземпляр, и предоставляет глобальную точку доступа к этому экземпляру.
Самый общий Singleton, которого хватает почти на 90% задач
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 { | |
private static Singleton instance; | |
public static synchronized Singleton getInstance() { | |
if (instance == null) { | |
instance = new Singleton(); | |
} | |
return instance; | |
} | |
} |
Какие у него плюсы и минусы:
- + ленивая инициализация
- - низкая производительность
Есть более продуктивный шаблон (Double Checked Locking & volatile)
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 { | |
public static volatile Singleton instance; | |
public static Singleton getInstance() { | |
Singleton local = instance; | |
if (local == null) { | |
synchronized(Singleton.class) { | |
local = instance; | |
if (local == null) { | |
instance = local = new Singleton(); | |
} | |
} | |
} | |
return instance; | |
} | |
} |
Какие у этого шаблона плюсы и минусы:
- + Ленивая инициализация
- + Высокая производительность
- - Поддерживается JDK5+
Есть еще и очень простой Singleton (Enum 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 enum Singleton { | |
INSTANCE; | |
} |
Какие у этого шаблона плюсы и минусы:
- + Сериализация из коробки
- + Потокобезопасность из коробки
- + Возможность использования EnumSet, EnumMap и т.д.
- + Поддержка switch
- - Неленивая инициализация
No comments:
Post a Comment