Skip to content

Instantly share code, notes, and snippets.

@sys1yagi
Last active December 10, 2015 17:08
Show Gist options
  • Save sys1yagi/4465396 to your computer and use it in GitHub Desktop.
Save sys1yagi/4465396 to your computer and use it in GitHub Desktop.
Implementation of logger based on adapter pattern in the Typescript
/** 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