Created
March 31, 2020 12:20
-
-
Save josser/34c61c5bb14c8b6287563fc1c6348992 to your computer and use it in GitHub Desktop.
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
interface StoreOptions { | |
} | |
interface DbStoreOptions extends StoreOptions { | |
dsn: string | |
} | |
interface FileStoreOptions extends DbStoreOptions { | |
path: string | |
} | |
interface StoreConstructor { | |
new(options: StoreOptions): IStore; | |
} | |
interface IStore { | |
get(): void; | |
} | |
function createStore(ctor: StoreConstructor, options: StoreOptions): IStore { | |
return new ctor(options); | |
} | |
export function factory(storeName: string, storeOptions: StoreOptions) { | |
const storeMap: { [index: string]: StoreConstructor } = { | |
db: DbStore, | |
file: FileStore | |
} | |
return createStore(storeMap[storeName], storeOptions) | |
} | |
class DbStore implements IStore { | |
constructor(options: DbStoreOptions) { } | |
get() { | |
console.log("beep beep"); | |
} | |
} | |
class FileStore implements IStore { | |
constructor(options: FileStoreOptions) { } | |
get() { | |
console.log("tick tock"); | |
} | |
} | |
// Usage: | |
const store = factory('file', { path: 'test' }) | |
store.get() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment