All quizzesEasy
Creational Patterns
Preview — 3 of 10 questions
What best describes a design pattern in programming?
javascript
// Singleton pattern: Only one instance of a class
class Logger {
static instance;
static getInstance() {
if (!Logger.instance) {
Logger.instance = new Logger();
}
return Logger.instance;
}
}
// Factory pattern: Create objects without specifying exact classes
class AnimalFactory {
static createAnimal(type) {
if (type === "dog") return new Dog();
if (type === "cat") return new Cat();
}
}
// Observer pattern: Notify multiple objects of state changes
class EventEmitter {
on(event, callback) { }
emit(event, data) { }
}AA template for writing HTML code.
BA reusable solution to a common problem in software design.
CA way to optimize JavaScript performance.
DA naming convention for variables and functions.
What does the Singleton pattern ensure?
javascript
class Database {
static instance;
constructor() {
if (Database.instance) {
return Database.instance; // Return existing instance
}
this.connection = null;
Database.instance = this;
}
connect() {
if (!this.connection) {
this.connection = "Connected to DB";
}
return this.connection;
}
}
const db1 = new Database();
const db2 = new Database();
console.log(db1 === db2); // true (same instance)AA class can have multiple instances.
BA class has only one instance and provides global access to it.
CA class creates a new instance for every method call.
DA class cannot be instantiated.
What does the Factory pattern do?
javascript
// Without Factory (client knows all classes)
const dog = new Dog();
const cat = new Cat();
const bird = new Bird();
// With Factory (client only knows factory)
class AnimalFactory {
static createAnimal(type) {
switch(type) {
case "dog": return new Dog();
case "cat": return new Cat();
case "bird": return new Bird();
}
}
}
const animal = AnimalFactory.createAnimal("dog");ACreates factories for manufacturing objects.
BEncapsulates object creation logic, allowing creation of objects without specifying exact classes.
CCreates a single object and reuses it.
DPrevents object creation.
Sign up free to play
Answer all 10 questions (7 more), see explanations for every answer, and track your score.