Created
November 17, 2018 17:36
-
-
Save sangheestyle/3ae63b64c0bd026f1682f88e9db1b3bb to your computer and use it in GitHub Desktop.
Practice the factory pattern in typescript
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { Person } from "./person"; | |
export class Adult extends Person { | |
getStatus(): void { | |
console.log('I am an adult!'); | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { PersonFactory } from "./factory"; | |
const people = [11, 12, 13, 14, 15].map(age => PersonFactory.createPerson(age)); | |
people.map(p => p.getStatus()); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { Person } from "./person"; | |
export class Child extends Person { | |
getStatus(): void { | |
console.log('I am a child!'); | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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