MSK Institute LogoMSK.Institute
HomeCourses
Book Free Demo➔Sign In
Free Demo➔
MSK Institute LogoMSK.Institute

Leading computer training academy in Shikohabad for software engineering, Python, web development, and digital literacy.

ISO 9001:2015 Certified Center
Follow & Connect
4.9

Programs & Admissions

  • All CoursesCatalog
  • Learning PathsRoadmaps
  • Student ProjectsShowcase
  • Live Classes & ScheduleLive
  • Upcoming Batches
  • Campuses & LocationsHub
  • Verify Certificates
  • Book Free Demo Class

Resources & Tools

  • Free Online Mock TestsAll Tests
  • NIELIT CCC Mock TestFree
  • Course & Career FinderQuiz
  • Study Material Hub
  • All MSK ToolsHub
  • Keyboard ShortcutsNew
  • TypeQuest Speed LabTyping
  • MSK Code PlaygroundCode
  • Interactive Tutorials
  • Quick Cheatsheets

Institute & Contact

  • About MSK Institute
  • Careers & InternshipsHiring
  • Publications & Blogs
  • Gali No. 3, Near Gyan Jyoti Public School,
    Adarsh Nagar, Shikohabad, Uttar Pradesh 283135
  • +91 83930 42166
  • mskshikohabad@gmail.com
  • Hours:Mon – Sat: 8:00 AM – 7:00 PM | Sun: 10:00 AM – 2:00 PM
  • 4.9 ★(38 Google Reviews)
© 2026 MSK Institute. All rights reserved.•Privacy Policy•Terms of Service•Disclaimer•Contact Us

Shikohabad's Leading Computer & Coding Academy

Home
Courses
Live
Material
Factory & Builder Patterns0%
Study Materials
JavaScript for AdvancedProgress 0%
1.1Higher-Order Functions & Currying1.2Function Composition & Pipelining1.3Memoization & Pure Functions1.4Execution Context & Call Stack Deep Dive1.5Scope Chain & Lexical Environment
9.1Singleton Pattern & Module Pattern9.2Factory & Builder Patterns9.3Observer & Pub/Sub Pattern9.4Strategy & State Patterns9.5Proxy & Decorator Patterns
HomeTutorialsJavaScript for AdvancedFactory & Builder Patterns
Observer & Pub/Sub Pattern

Factory & Builder Patterns

Beginner12 min read•Updated: 2026-11-18•By Er. Sumit Kumar (MSK Institute)
Study Materials

As software systems grow in complexity, instantiating objects using raw new constructor calls with dozens of parameters leads to unwieldy code. The Factory Pattern and the Builder Pattern are creational patterns that abstract and organize complex object construction.


1. The Factory Pattern

The Factory Pattern provides an interface for creating objects without specifying their exact concrete classes, delegating the instantiation logic based on parameters or environment conditions:

1class EmailNotification {
2 send(user, msg) { console.log(`[Email to ${user.email}]: ${msg}`); }
3}
4 
5class SMSNotification {
6 send(user, msg) { console.log(`[SMS to ${user.phone}]: ${msg}`); }
7}
8 
9class PushNotification {
10 send(user, msg) { console.log(`[Push to Device ${user.deviceId}]: ${msg}`); }
11}
12 
13// Factory Class
14class NotificationFactory {
15 static createNotification(channel) {
16 switch (channel.toLowerCase()) {
17 case 'email': return new EmailNotification();
18 case 'sms': return new SMSNotification();
19 case 'push': return new PushNotification();
20 default:
21 throw new Error(`Unsupported notification channel: "${channel}"`);
22 }
23 }
24}
25 
26// Consumer code does not depend on concrete classes:
27const service = NotificationFactory.createNotification('sms');
28service.send({ phone: '+1-555-0199' }, 'Your verification code is 4920');

2. The Builder Pattern

The Builder Pattern separates the construction of a complex object from its representation, allowing the same construction process to create various representations using fluent method chaining:

Solving the "Telescoping Constructor" Anti-Pattern:

1// ANTI-PATTERN: Telescoping constructor with 7 parameters (confusing & error-prone!)
2// new HttpRequest('https://api.com', 'POST', null, { 'Auth': '...' }, 5000, true, 'json');

Clean Builder Pattern Implementation:

1class HttpRequest {
2 constructor(builder) {
3 this.url = builder.url;
4 this.method = builder.method;
5 this.headers = builder.headers;
6 this.body = builder.body;
7 this.timeout = builder.timeout;
8 this.requiresAuth = builder.requiresAuth;
9 }
10 
11 async execute() {
12 console.log(`Sending ${this.method} to ${this.url}`);
13 return fetch(this.url, {
14 method: this.method,
15 headers: this.headers,
16 body: this.body ? JSON.stringify(this.body) : undefined
17 });
18 }
19}
20 
21class HttpRequestBuilder {
22 constructor(url) {
23 this.url = url;
24 this.method = 'GET';
25 this.headers = {};
26 this.body = null;
27 this.timeout = 3000;
28 this.requiresAuth = false;
29 }
30 
31 setMethod(method) {
32 this.method = method.toUpperCase();
33 return this; // Return 'this' for fluent chaining!
34 }
35 
36 setHeader(key, value) {
37 this.headers[key] = value;
38 return this;
39 }
40 
41 setBody(data) {
42 this.body = data;
43 this.headers['Content-Type'] = 'application/json';
44 return this;
45 }
46 
47 setTimeout(ms) {
48 this.timeout = ms;
49 return this;
50 }
51 
52 requireAuth() {
53 this.requiresAuth = true;
54 return this;
55 }
56 
57 // Final Step: Builds the HttpRequest object!
58 build() {
59 return new HttpRequest(this);
60 }
61}
62 
63// Usage: Fluent, self-documenting code
64const request = new HttpRequestBuilder('https://api.example.com/v1/users')
65 .setMethod('POST')
66 .setHeader('Accept', 'application/json')
67 .setBody({ username: 'sarah_dev', role: 'admin' })
68 .requireAuth()
69 .setTimeout(5000)
70 .build();
71 
72request.execute();

3. Comparing Factory vs. Builder

FeatureFactory PatternBuilder Pattern
FocusDeciding which concrete subclass to createConstructing a complex object step-by-step
Syntax StyleSingle method call (create(type))Fluent method chaining (.set().set().build())
ComplexitySimple polymorphismHigh configuration flexibility with many optional parameters

Interactive Quiz• Knowledge Check

Practice Quiz

Question 1
What is the primary purpose of the Factory Pattern?
Question 2
What problem does the Builder Pattern solve?
Question 3
Why do builder methods (like setMethod() or setHeader()) return this?
Question 4
Which method is conventionally invoked as the final step in a Builder class to return the constructed object?
Question 5
If an application needs to instantiate different database drivers (Postgres, Mongo, SQLite) based on environment configuration, which pattern is best?
Next Lesson

Observer & Pub/Sub Pattern

Continue learning with hands-on practice, examples, and exercises in the upcoming topic.

Related Lessons

Previous LessonNext Lesson
Singleton Pattern & Module PatternObserver & Pub/Sub Pattern

Practice Quiz

Test your understanding of this lesson with 5 questions. Each question has one correct answer.

Mentor-Led Practical Training

Master JavaScript for Advanced with Hands-On Projects

Practice in live mentor-led sessions with real projects, mock tests, and verifiable certification at MSK Institute.

View Full CourseBook Free Demo
PreviousNext
PreviousPrevNext