Skip to content

Instantly share code, notes, and snippets.

@mul14
Last active April 5, 2018 12:42
Show Gist options
  • Save mul14/7f8e8cb1f966e26fd85e2dc9e28e67b5 to your computer and use it in GitHub Desktop.
Save mul14/7f8e8cb1f966e26fd85e2dc9e28e67b5 to your computer and use it in GitHub Desktop.
Adapter pattern implementation on JavaScript
import { EOL } from 'os';
interface LoggerInterface {
error(message: string): string
info(message: string): string
}
class Logger implements LoggerInterface {
adapter = null
constructor(adapter) {
this.adapter = adapter
}
error(message: string): string {
return this.adapter.error(message)
}
info(message: string): string {
return this.adapter.info(message)
}
}
class ShortTimestampLogger implements LoggerInterface {
logger(message, level = 'INFO') {
const date = new Date().toDateString()
return `[${date}] ${level}: ${message}${EOL}`
}
error(message: string): string {
return this.logger(message, 'ERROR')
}
info(message: string): string {
return this.logger(message, 'INFO')
}
}
class LongTimestampLogger implements LoggerInterface {
logger(message, level = 'INFO') {
const date = new Date().toString()
return `[${date}] ${level}: ${message}${EOL}`
}
error(message: string): string {
return this.logger(message, 'ERROR')
}
info(message: string): string {
return this.logger(message, 'INFO')
}
}
const shorterLogger = new Logger(new ShortTimestampLogger)
shorterLogger.info('This message use short timestamp.')
const longLogger = new Logger(new LongTimestampLogger)
shorterLogger.info('This message use long timestamp.')
class Storage {
constructor(storage) {
this.storage = storage
}
put(key, value) {
this.storage.put(key, value)
}
get(key) {
this.storage.get(key)
}
}
class LocalStorage {
static put(key, value) {
localStorage.setItem(key, value)
console.log('put', key, value)
}
static get(key) {
localStorage.getItem(key)
console.log('get', value)
}
}
class Cookie {
static put(key, value) {
console.log('put', key, value)
}
static get(key) {
console.log('get', value)
}
}
class Redis {
static put(key, value) {
console.log('put', key, value)
}
static get(key) {
console.log('get', value)
}
}
const storage = new Storage(LocalStorage)
storage.put('lang', 'id')
storage.get('lang') // Output: id
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment