Logo
Section 1 / 19

理解策略模式

学习如何通过在公共接口后封装算法,并在运行时选择使用哪一个,来干净地将一种行为替换为另一种。

导入

理解策略模式

学习如何通过在公共接口后封装算法,并在运行时选择使用哪一个,来干净地将一种行为替换为另一种。

...
The Strategy Pattern selects the appropriate authentication method at runtime

Node.js

1// --- Strategies: each defines `authenticate()` --- 2class PasswordLogin { 3 authenticate({ username, password }) { 4 console.log(`[PasswordLogin] Authenticating ${username}`); 5 return password === "secret"; 6 } 7} 8 9class OtpLogin { 10 authenticate({ phone, otp }) { 11 console.log(`[OtpLogin] Verifying ${phone} with code ${otp}`); 12 return otp === 1234; 13 } 14} 15 16class GoogleLogin { 17 authenticate({ token }) { 18 console.log(`[GoogleLogin] Checking Google token: ${token}`); 19 return token.startsWith("valid-"); 20 } 21} 22 23// --- Context: delegates to whichever strategy is active --- 24class AuthService { 25 constructor(strategy) { 26 this.strategy = strategy; 27 } 28 29 setStrategy(strategy) { 30 this.strategy = strategy; 31 } 32 33 login(credentials) { 34 if (!this.strategy) throw new Error("No strategy set"); 35 const ok = this.strategy.authenticate(credentials); 36 console.log(`Login ${ok ? "successful" : "failed"}\n`); 37 return ok; 38 } 39} 40 41// --- Usage --- 42const auth = new AuthService(new PasswordLogin()); 43auth.login({ username: "alice", password: "secret" }); 44 45auth.setStrategy(new OtpLogin()); 46auth.login({ phone: "+15551234", otp: 1234 }); 47 48auth.setStrategy(new GoogleLogin()); 49auth.login({ token: "valid-xyz" });

TypeScript

1interface LoginStrategy { 2 authenticate(credentials: any): boolean; 3} 4 5// --- Strategies: each defines `authenticate()` --- 6class PasswordLogin implements LoginStrategy { 7 authenticate({ username, password }: any): boolean { 8 console.log(`[PasswordLogin] Authenticating ${username}`); 9 return password === "secret"; 10 } 11} 12 13class OtpLogin implements LoginStrategy { 14 authenticate({ phone, otp }: any): boolean { 15 console.log(`[OtpLogin] Verifying ${phone} with code ${otp}`); 16 return otp === 1234; 17 } 18} 19 20class GoogleLogin implements LoginStrategy { 21 authenticate({ token }: any): boolean { 22 console.log(`[GoogleLogin] Checking Google token: ${token}`); 23 return token.startsWith("valid-"); 24 } 25} 26 27// --- Context: delegates to whichever strategy is active --- 28class AuthService { 29 constructor(private strategy: LoginStrategy) {} 30 31 setStrategy(strategy: LoginStrategy) { 32 this.strategy = strategy; 33 } 34 35 login(credentials: any): boolean { 36 const ok = this.strategy.authenticate(credentials); 37 console.log(`Login ${ok ? "successful" : "failed"}\n`); 38 return ok; 39 } 40} 41 42// --- Usage --- 43const auth = new AuthService(new PasswordLogin()); 44auth.login({ username: "alice", password: "secret" }); 45 46auth.setStrategy(new OtpLogin()); 47auth.login({ phone: "+15551234", otp: 1234 }); 48 49auth.setStrategy(new GoogleLogin()); 50auth.login({ token: "valid-xyz" });

代理模式:透明地拦截和控制访问

使用可插拔算法对报告进行排序