Skip to content

Instantly share code, notes, and snippets.

@sangheestyle
Created November 17, 2018 17:36
Show Gist options
  • Save sangheestyle/3ae63b64c0bd026f1682f88e9db1b3bb to your computer and use it in GitHub Desktop.
Save sangheestyle/3ae63b64c0bd026f1682f88e9db1b3bb to your computer and use it in GitHub Desktop.
Practice the factory pattern in typescript
import { Person } from "./person";
export class Adult extends Person {
getStatus(): void {
console.log('I am an adult!');
}
}
import { PersonFactory } from "./factory";
const people = [11, 12, 13, 14, 15].map(age => PersonFactory.createPerson(age));
people.map(p => p.getStatus());
import { Person } from "./person";
export class Child extends Person {
getStatus(): void {
console.log('I am a child!');
}
}
import { Adult } from "./adult";
import { Child } from "./child";
import { Person } from "./person";
export class PersonFactory {
public static createPerson(age: number): Person {
return age > 12 ? new Adult(age) : new Child(age);
}
}
export abstract class Person {
private age: number;
constructor(age: number) {
this.age = age;
}
abstract getStatus(): void;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment