Skip to content

Instantly share code, notes, and snippets.

@josser
Created March 31, 2020 12:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save josser/34c61c5bb14c8b6287563fc1c6348992 to your computer and use it in GitHub Desktop.
Save josser/34c61c5bb14c8b6287563fc1c6348992 to your computer and use it in GitHub Desktop.
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