JavaScript
Singleton deseni
Bir sınıftan yalnızca tek örnek oluşmasını sağlayan Singleton desenini öğrenirsin.
Singleton deseni
Singleton deseni, bir sınıftan yalnızca tek örnek (instance) oluşturulmasını sağlar. Genellikle yapılandırma, önbellek veya bağlantı gibi tek olması gereken durumlar için kullanılır.
JavaScript'te bunu static bir instance özelliği ve yapıcı içinde bir kontrol ile yaparız. Eğer örnek zaten varsa onu döndürürüz; yoksa yeni örnek oluşturup saklarız.
Böylece aynı yapılandırma nesnesi her yerde paylaşılır.
Singleton uygulaması
Singleton uygulamak için static instance = null ile başlarız. Yapıcı, eğer AppConfig.instance doluysa onu döndürür; değilse this'i AppConfig.instance'a atar.
Genellikle bir static getInstance() yöntemi de eklenir; böylece çağıran kod new kullanmak yerine bu yöntemi çağırır.
class AppConfig {
static instance = null;
constructor() {
if (AppConfig.instance) return AppConfig.instance;
AppConfig.instance = this;
}
}
Uygulama AppConfig singleton
Adı AppConfig olan bir Singleton sınıfı tanımla. static instance = null ile başlasın. Yapıcısı, eğer AppConfig.instance doluysa onu döndürsün; değilse this'i AppConfig.instance'a atasın.
Örnek çözümü göster
class AppConfig ile başla, static instance = null ekle, yapıcıda if (AppConfig.instance) return AppConfig.instance; yap, sonra AppConfig.instance = this ata.
Örnek çözüm:
class AppConfig {
static instance = null;
constructor() {
if (AppConfig.instance) return AppConfig.instance;
AppConfig.instance = this;
}
}
Kendini test et
-
Singleton deseninin temel amacı nedir?
- Bir sınıftan yalnızca tek örnek olmasını sağlamak
- Nesneleri sıralamak
- Çok sayıda örnek üretmek
- Sınıfı gizlemek
Cevabı göster
Bir sınıftan yalnızca tek örnek olmasını sağlamak — Doğru! Singleton, tek örnek garantisi verir.
-
Singleton atamasını tamamla
class AppConfig {
static instance = null;
constructor() {
if (AppConfig.instance) return AppConfig.instance;
AppConfig.instance = ____;
}
}
Cevabı göster
class AppConfig {
static instance = null;
constructor() {
if (AppConfig.instance) return AppConfig.instance;
AppConfig.instance = this;
}
}
-
Singleton kavramlarını eşleştir
- Singleton
- Tek örnek garantisi
- static instance
- Sınıf düzeyinde tek örnek
- getInstance()
- Örneğe erişim yöntemi
- Lazy init
- İlk istekte oluşturma
Sıradaki ders: Factory deseni