daily pastebin goal
28%
SHARE
TWEET

Strategy Pattern Typescript

a guest Oct 20th, 2018 78 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. interface ILogger {
  2.     error(message: string): void;
  3.  
  4.     info(message: string): void;
  5.  
  6.     warning(message: string): void;
  7. }
  8.  
  9. /**
  10.  * DB Logger
  11.  */
  12. class DBLogger implements ILogger {
  13.     public error(message: string): void {
  14.         // do something
  15.     }
  16.  
  17.     public info(message: string): void {
  18.         // do something
  19.     }
  20.  
  21.     public warning(message: string): void {
  22.         // do something
  23.     }
  24. }
  25.  
  26. /**
  27.  * File Logger
  28.  */
  29. class FileLogger implements ILogger {
  30.     public error(message: string): void {
  31.         // do something
  32.     }
  33.  
  34.     public info(message: string): void {
  35.         // do something
  36.     }
  37.  
  38.     public warning(message: string): void {
  39.         // do something
  40.     }
  41. }
  42.  
  43. class Logger {
  44.     private loggerInstance: ILogger;
  45.  
  46.     /**
  47.      * Constructor Logger.
  48.      *
  49.      * @param inst
  50.      */
  51.     public constructor(inst: ILogger) {
  52.         this.loggerInstance = inst;
  53.     }
  54.  
  55.     /**
  56.      * Set Error log.
  57.      * @param message
  58.      */
  59.     public error(message: string) {
  60.         this.loggerInstance.error(message);
  61.     }
  62.  
  63.     /**
  64.      * Set Info log.
  65.      * @param message
  66.      */
  67.     public info(message: string) {
  68.         this.loggerInstance.info(message);
  69.     }
  70.  
  71.     /**
  72.      * Set Warning log.
  73.      * @param message
  74.      */
  75.     public warning(message: string) {
  76.         this.loggerInstance.warning(message);
  77.     }
  78.  
  79.     /**
  80.      * Set new logger instance.
  81.      *
  82.      * @param inst
  83.      */
  84.     public setLogger(inst: ILogger) {
  85.         this.loggerInstance = inst;
  86.     }
  87. }
  88.  
  89. const dbLogger = new DBLogger();
  90.  
  91. const logger = new Logger(dbLogger);
  92. logger.error('Error line');
  93.  
  94. logger.setLogger(new FileLogger());
  95. logger.warning('Warning line');
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
 
Top