Node.js
Soru ekleme
addQuestion metoduyla quiz'e soru eklemeyi öğrenirsin.
Quiz sınıfı ve addQuestion
Şimdi Quiz sınıfını tanımlayacağız. Bu sınıf soruları bir dizide saklar. constructor boş bir dizi oluşturur: this.questions = [];. addQuestion metodu yeni bir soru ekler.
addQuestion(text, answer) metodu otomatik id üretir: const id = this.questions.length + 1;. Sonra new Question(id, text, answer) ile nesneyi yapıp this.questions.push(...) ile diziye ekler. Bu, bir kurucu (builder) desenidir: her çağrıda bir soru eklenir ve quiz büyür. Önceki dersin Question sınıfını alıp Quiz sınıfını ekleyeceğiz. Böylece quiz, soruları yöneten bir kapsayıcı olur.
Builder deseni
addQuestion bir builder desenidir. Her çağrı quiz'e bir soru ekler. Örnek: quiz.addQuestion("Başkent?", "Ankara"); quiz.addQuestion("En büyük şehir?", "İstanbul");. İki çağrıdan sonra quiz.questions.length 2 olur.
Builder deseni, nesneleri adım adım kurmanın temel yoludur. Tek bir kurucu ile tüm veriyi vermek yerine, her parçayı ayrı bir metotla eklersin. Bu, kodu okunaklı kılar: her addQuestion çağrısı tek bir soru tanımlar. Ayrıca id otomatik üretildiği için, çağrı sırası id'yi belirler. İlk çağrı id=1, ikinci id=2. Bu, quiz'in tutarlı kalmasını sağlar.
Uygulama Quiz sınıfını ve addQuestion metodunu ekle
Önceki dersin Question sınıfını al. class Quiz ekle: constructor'da this.questions = [], addQuestion(text, answer) metodunda const id = this.questions.length + 1; this.questions.push(new Question(id, text, answer));. Son satırlar hazır: iki soru ekle ve sayıyı yazdır.
Örnek çözümü göster
class Question {
constructor(id, text, answer) {
this.id = id;
this.text = text;
this.answer = answer;
}
}
class Quiz {
constructor() {
this.questions = [];
}
addQuestion(text, answer) {
const id = this.questions.length + 1;
this.questions.push(new Question(id, text, answer));
}
}
const quiz = new Quiz();
quiz.addQuestion("Başkent?", "Ankara");
quiz.addQuestion("En büyük şehir?", "İstanbul");
console.log("Soru sayısı: " + quiz.questions.length);
Kendini test et
-
addQuestion gövdesini tamamla
addQuestion(text, answer) {
const id = this.questions.length + 1;
this.questions.____(new Question(id, text, answer));
}
Cevabı göster
addQuestion(text, answer) {
const id = this.questions.length + 1;
this.questions.push(new Question(id, text, answer));
}
-
Parçayı rolüne eşle
- this.questions
- Soru dizisi
- addQuestion
- Soru ekler
- questions.length + 1
- Yeni id üretir
- new Question
- Soru nesnesi oluşturur
-
quiz.addQuestion çağrıldığında ne olur?
quiz.addQuestion("Soru?", "Cevap")
- İlk soru güncellenir
- Quiz silinir
- Yeni soru dizinin sonuna eklenir
- Soru sayısı azalır
Cevabı göster
Yeni soru dizinin sonuna eklenir — addQuestion yeni soruyu dizinin sonuna ekler.
Sıradaki ders: Quiz oynatma