Skip to content

Instantly share code, notes, and snippets.

@trikitrok
Last active March 22, 2025 12:32
Show Gist options
  • Save trikitrok/4eeaa019d60dba1f976d3f951739186c to your computer and use it in GitHub Desktop.
Save trikitrok/4eeaa019d60dba1f976d3f951739186c to your computer and use it in GitHub Desktop.
Wrap Class example
//////////////////////////////////////////////////
// Step 1: Identify the change point
export class Employee {
public timeCards: TimeCard[];
public payPeriod: Date[];
public date: Date;
public payRate: number;
public payDispatcher: PayDispatcher;
public pay(): void {
const amount = new Money();
for (const card of this.timeCards) {
if (this.payPeriod.includes(this.date)) {
amount.add(card.hours * this.payRate);
}
}
this.payDispatcher.pay(this, this.date, amount);
// <-- this is the change point
}
}
//////////////////////////////////////////////////
// Step 2: Create a class that accepts the class we are going to wrap as a constructor argument
export class LoggingEmployee {
private readonly employee: Employee;
constructor(employee: Employee) {
this.employee = employee;
}
}
//////////////////////////////////////////////////
// Step 3: Create a method on the wrapper class with tests, that does the new behaviour and calls the old behaviour on the wrapper class
export class LoggingEmployee {
private readonly employee: Employee;
private readonly logger: Logger;
constructor(employee: Employee, logger: Logger) {
this.employee = employee;
this.logger = logger;
}
public pay(): void { // <-- pay with logging
this.employee.pay(); // <-- delegates to original method
this.logPayment(); // <-- logs the payment
}
private logPayment(): void {
// log employee data
}
}
//////////////////////////////////////////////////
// Step 4: Instantiate the wrapper class in your code in the place where you need to enable the new behavior
export class Client {
public someMethod(): void {
const employee = new LoggingEmployee(new Employee(), new AcmeLogger());
employee.pay();
// rest of the code omitted for brevity...
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment