Skip to content

Instantly share code, notes, and snippets.

@semlinker
Created November 30, 2022 01:50
Show Gist options
  • Save semlinker/6274c467591e41e50f6540aecac9aaea to your computer and use it in GitHub Desktop.
Save semlinker/6274c467591e41e50f6540aecac9aaea to your computer and use it in GitHub Desktop.
Strategy Patterns
interface Strategy {
authenticate(args: any[]): boolean;
}
class Authenticator {
strategies: Record<string, Strategy> = {};
use(name: string, strategy: Strategy) {
this.strategies[name] = strategy;
}
authenticate(name: string, ...args: any) {
if (!this.strategies[name]) {
console.error("Authentication policy has not been set!");
return false;
}
return this.strategies[name].authenticate.apply(null, args);
}
}
class WechatStrategy implements Strategy {
authenticate(args: any[]) {
const [token] = args;
if (token !== "wc123456") {
console.error("Wechat account authentication failed!");
return false;
}
console.log("Wechat account authentication succeeded!");
return true;
}
}
class LocalStrategy implements Strategy {
authenticate(args: any[]) {
const [username, password] = args;
if (username !== "semlinker" || password !== "888") {
console.log("Incorrect username or password!");
return false;
}
console.log("Account and password authentication succeeded!");
return true;
}
}
const auth = new Authenticator();
auth.use("wechat", new WechatStrategy());
auth.use("local", new LocalStrategy());
function login(mode: string, ...args: any) {
return auth.authenticate(mode, args);
}
login("wechat", "wc123");
login("local", "semlinker", "666");
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment