F

Factory Pattern

The Factory pattern creates objects without exposing instantiation logic.

Code

typescript
1// Product interface
2interface Logger {
3 log(message: string): void;
4 error(message: string): void;
5 warn(message: string): void;
6}
7
8// Concrete implementations
9class ConsoleLogger implements Logger {
10 log(message: string): void {
11 console.log(`[LOG] ${message}`);
12 }
13
14 error(message: string): void {
15 console.error(`[ERROR] ${message}`);
16 }
17
18 warn(message: string): void {
19 console.warn(`[WARN] ${message}`);
20 }
21}
22
23class FileLogger implements Logger {
24 constructor(private filename: string) {}
25
26 private write(level: string, message: string): void {
27 const entry = `[${new Date().toISOString()}] [${level}] ${message}\n`;
28 // In real implementation, write to file
29 console.log(`Writing to ${this.filename}: ${entry.trim()}`);
30 }
31
32 log(message: string): void {
33 this.write("LOG", message);
34 }
35
36 error(message: string): void {
37 this.write("ERROR", message);
38 }
39
40 warn(message: string): void {
41 this.write("WARN", message);
42 }
43}
44
45class JsonLogger implements Logger {
46 private emit(level: string, message: string): void {
47 const entry = JSON.stringify({
48 timestamp: new Date().toISOString(),
49 level,
50 message,
51 });
52 console.log(entry);
53 }
54
55 log(message: string): void {
56 this.emit("info", message);
57 }
58
59 error(message: string): void {
60 this.emit("error", message);
61 }
62
63 warn(message: string): void {
64 this.emit("warn", message);
65 }
66}
67
68// Factory
69type LoggerType = "console" | "file" | "json";
70
71interface LoggerConfig {
72 type: LoggerType;
73 filename?: string;
74}
75
76class LoggerFactory {
77 static create(config: LoggerConfig): Logger {
78 switch (config.type) {
79 case "console":
80 return new ConsoleLogger();
81 case "file":
82 if (!config.filename) {
83 throw new Error("Filename required for file logger");
84 }
85 return new FileLogger(config.filename);
86 case "json":
87 return new JsonLogger();
88 default:
89 throw new Error(`Unknown logger type: ${config.type}`);
90 }
91 }
92}
93
94// Usage
95const consoleLogger = LoggerFactory.create({ type: "console" });
96consoleLogger.log("Application started");
97
98const fileLogger = LoggerFactory.create({
99 type: "file",
100 filename: "app.log"
101});
102fileLogger.error("Something went wrong");
103
104const jsonLogger = LoggerFactory.create({ type: "json" });
105jsonLogger.warn("Low memory warning");

Run this example locally

$ npx ts-node patterns/factory.ts