Last active
June 6, 2018 16:53
-
-
Save neerajkumar/f4f98dee650d0c6ce6151fa80668853b to your computer and use it in GitHub Desktop.
Design Pattern: Decorator Pattern - Javascript Solution
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
let fs = require('fs'); | |
// ConcreteComponent | |
class SimpleWriter { | |
constructor(path) { | |
this.file_path = path; | |
} | |
writeLine(line) { | |
let self = this | |
fs.appendFile(this.file_path, line + '\n', function (err, file) { | |
if (err) throw err; | |
console.log(`File ${self.file_path} created and opened`); | |
}); | |
} | |
pos() { | |
} | |
rewind() { | |
} | |
close() { | |
fs.closeFile(this.file_path); | |
} | |
} | |
// Decorator | |
class WriterDecorator { | |
constructor(real_writer) { | |
this.real_writer = real_writer; | |
} | |
writeLine(line) { | |
this.real_writer.writeLine(line); | |
} | |
close() { | |
this.real_writer.close(); | |
} | |
} | |
// Component | |
class NumberingWriter extends WriterDecorator { | |
constructor(real_writer) { | |
super(real_writer); | |
this.line_number = 1; | |
} | |
writeLine(line) { | |
this.real_writer.writeLine(this.line_number + ': ' + line); | |
} | |
} | |
// Component | |
class CheckSummingWriter extends WriterDecorator { | |
constructor(real_writer) { | |
this.check_sum = 0; | |
} | |
writeLine(line) { | |
} | |
} | |
// Component | |
class TimeStampingWriter extends WriterDecorator { | |
writeLine(line) { | |
this.real_writer.writeLine(new Date() + ': ' + line); | |
} | |
} | |
let writer = new TimeStampingWriter(new NumberingWriter(new SimpleWriter("final.txt"))); | |
writer.writeLine('Hello Out There'); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment