Code Organization Patterns
Factory Functions
A factory function creates a configured object without exposing setup details to callers.
Factory Functions
factory.ts
type Counter = {
increment(): void;
value(): number;
};
function createCounter(start: number): Counter {
let current: number = start;
return {
increment(): void {
current = current + 1;
},
value(): number {
return current;
},
};
}
const startValue: number = ;
const counter: Counter = createCounter(startValue);
counter.increment();
counter.increment();
console.log(`value=${counter.value()}`);
type Counter = {
increment(): void;
value(): number;
};
function createCounter(start: number): Counter {
let current: number = start;
return {
increment(): void {
current = current + 1;
},
value(): number {
return current;
},
};
}
const startValue: number = ;
const counter: Counter = createCounter(startValue);
counter.increment();
counter.increment();
console.log(`value=${counter.value()}`);
type Counter = {
increment(): void;
value(): number;
};
function createCounter(start: number): Counter {
let current: number = start;
return {
increment(): void {
current = current + 1;
},
value(): number {
return current;
},
};
}
const startValue: number = ;
const counter: Counter = createCounter(startValue);
counter.increment();
counter.increment();
console.log(`value=${counter.value()}`);
factory function
A factory function returns a new object that already has the data and methods it needs.