Last active
October 21, 2022 15:41
-
-
Save GuyHarwood/54f7918142feb12fe61ba94412a4c343 to your computer and use it in GitHub Desktop.
Decorator pattern example in Typescript
This file contains 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
// decorator example | |
export interface IWork { | |
doWork (work: any): void | |
} | |
export class ImportantService implements IWork { | |
doWork (work: any): void { | |
// important work done here | |
} | |
} | |
export class MyAuditor implements IWork { | |
serviceToAudit: IWork | |
constructor (serviceToAudit: IWork) { | |
this.serviceToAudit = serviceToAudit | |
} | |
doWork (work: any): void { | |
this.audit(work) | |
this.serviceToAudit.doWork(work) | |
} | |
private audit (something: any) { | |
// do some auditing | |
console.log(something) | |
} | |
} | |
export class RetryService implements IWork { | |
private maxRetries = 3 | |
private serviceToRetry: IWork | |
constructor (serviceToRetry: IWork) { | |
this.serviceToRetry = serviceToRetry | |
} | |
private tryWork (work: any) { | |
this.serviceToRetry.doWork(work) | |
} | |
doWork (work: any): void { | |
var tries = 0 | |
try { | |
this.tryWork(work) | |
} catch (error) { | |
tries++ | |
if (tries < this.maxRetries) | |
{ | |
this.tryWork(work) | |
} else { | |
throw error | |
} | |
} | |
} | |
} | |
const resolveImportantService = () => { | |
const importantService = new ImportantService() | |
const retrier = new RetryService(importantService) | |
const auditor = new MyAuditor(retrier) | |
return auditor | |
} | |
function myClientCode () { | |
const service = resolveImportantService() | |
service.doWork('some work to do') | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment