Last active
December 10, 2015 17:08
-
-
Save sys1yagi/4465396 to your computer and use it in GitHub Desktop.
Implementation of logger based on adapter pattern in the 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
/** A unified logging interface */ | |
interface Logger{ | |
log(msg: string): void; | |
} | |
/** Factory for enums */ | |
class LOGGER_TYPE{ | |
static CONSOLE:string="CONSOLE"; | |
static ALERT:string="ALERT"; | |
static DISPLAY:string="DISPLAY"; | |
} | |
class LogAdapterFactory{ | |
static createLogger(type:string): Logger{ | |
switch(type){ | |
case LOGGER_TYPE.CONSOLE: | |
return new ConsoleLogger(); | |
case LOGGER_TYPE.ALERT: | |
return new AlertLogger(); | |
case LOGGER_TYPE.DISPLAY: | |
return new DisplayLogger(); | |
} | |
return null; | |
} | |
} | |
class ConsoleLogger implements Logger{ | |
log(msg:string){ | |
console.log(msg); | |
} | |
} | |
class AlertLogger implements Logger{ | |
log(msg:string){ | |
alert(msg); | |
} | |
} | |
class DisplayLogger implements Logger{ | |
display:HTMLDivElement; | |
count:number; | |
constructor(){ | |
this.count = 0; | |
this.display = <HTMLDivElement>document.createElement("div"); | |
this.display.style.position="absolute"; | |
this.display.style.top="0px"; | |
this.display.style.right="0px"; | |
this.display.style.width="200px"; | |
this.display.style.background="#ddffdd"; | |
this.display.style.padding="10px"; | |
this.display.style.fontSize="10px"; | |
document.body.appendChild(this.display); | |
} | |
log(msg:string){ | |
if(this.count > 10){ | |
this.display.removeChild(this.display.childNodes[0]); | |
} | |
else{ | |
this.count++; | |
} | |
this.display.innerHTML += "<div>"+msg+"</div>"; | |
} | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment