Skip to content

Instantly share code, notes, and snippets.

@odanado
Last active January 22, 2021 12:52
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 odanado/12a7708779396f05f51c9360c688343f to your computer and use it in GitHub Desktop.
Save odanado/12a7708779396f05f51c9360c688343f to your computer and use it in GitHub Desktop.
abstract class BaseCommand<T> {
abstract parse(argv: string): T;
abstract run(config: T): void;
}
// parse と run の実装とインタフェースを矯正させる
class CommandA extends BaseCommand<{}> {
parse(argv: string) {
return {}
}
run(config: {}) {
}
}
type CommandBConfig = {hoge:number}
class CommandB extends BaseCommand<CommandBConfig> {
parse(argv: string) {
return {hoge: 10}
}
run(config: CommandBConfig) {
}
}
abstract class BaseCommand<T> {
abstract parse(argv: string): T;
abstract run(config: T): void;
initAndRun(argv: string) {
this.run(this.parse(argv))
}
}
// parse と run の実装とインタフェースを矯正させて、initAndRun でまとめられる
class CommandA extends BaseCommand<{}> {
parse(argv: string) {
return {}
}
run(config: {}) {
}
}
type CommandBConfig = {hoge:number}
class CommandB extends BaseCommand<CommandBConfig> {
parse(argv: string) {
return {hoge: 10}
}
run(config: CommandBConfig) {
}
}
@sonatard
Copy link

sonatard commented Jan 22, 2021

// parse と run の実装とインタフェースを強制させる
class CommandA implements BaseCommand<{}> {
  parse(argv: string) {
    return {};
  }
  run(config: {}) {}
}

type CommandBConfig = { hoge: number };
class CommandB implements BaseCommand<CommandBConfig> {
  parse(argv: string) {
    return { hoge: 10 };
  }
  run(config: CommandBConfig) {}
}

class CommandExecutor<T> {
  cmd: BaseCommand<T>;
  constructor(command: BaseCommand<T>) {
    this.cmd = command;
  }
  exec(argv: string) {
    this.cmd.run(this.cmd.parse(argv));
  }
}

// CommandExecutorに委譲する
new CommandExecutor(new CommandB()).exec("aaa");

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment