Last active
April 29, 2022 16:19
-
-
Save danywalls/27c843a0b3e5628266062fd00974ff4a to your computer and use it in GitHub Desktop.
adapter example
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
class Item { | |
key: string; | |
value: string; | |
} | |
interface IStorage { | |
getItem(key: string): Item; | |
setItem(item: Item): boolean; | |
remove(key: string): boolean; | |
} | |
// aqui uso el stragety | |
export class StoreWrapper { | |
private storeManager: IStorage; | |
constructor(storage: IStorage) { | |
this.setStorage(storage); | |
} | |
setStorage(storage: IStorage): void { | |
this.storeManager = storage; | |
} | |
getItem(key: string): Item { | |
return this.storeManager.getItem(key); | |
} | |
setItem(item: Item): boolean { | |
return this.storeManager.setItem(item); | |
} | |
removeItem(key: string): boolean { | |
return this.storeManager.remove(key); | |
} | |
} | |
class StoreManagerGoogle implements IStorage { | |
getItem(key: string): Item { | |
return { key, value: 'google' }; | |
} | |
setItem(item: Item): boolean { | |
return true; | |
} | |
remove(key: string): boolean { | |
return true; | |
} | |
} | |
class StoreManagerFacebook implements IStorage { | |
getItem(key: string): Item { | |
return { key, value: 'facebook' }; | |
} | |
setItem(item: Item): boolean { | |
return true; | |
} | |
remove(key: string): boolean { | |
return true; | |
} | |
} | |
// el singelton | |
export class StoreManagerWrapper { | |
private static storeWrapper: StoreWrapper; | |
private constructor() {} | |
public static getInstanceOf(storage: IStorage): StoreWrapper { | |
if (!this.storeWrapper) { | |
this.storeWrapper = new StoreWrapper(storage); | |
} | |
return this.storeWrapper; | |
} | |
} | |
const googleStorage = new StoreManagerGoogle(); | |
const facebookStorage = new StoreManagerFacebook(); | |
const storeManager = StoreManagerWrapper.getInstanceOf(googleStorage); | |
storeManager.setItem({ key: 'a', value: 'item' }); | |
let value = storeManager.getItem('hello'); | |
console.log(value);storeManager.setStorage(facebookStorage); | |
storeManager.setItem({ key: 'a', value: 'item' }); | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment