1+ /**
2+ * DEMO1
3+ */
4+
15interface Strategy < T > {
26 execute ( data : T ) : T
37}
@@ -33,4 +37,58 @@ context.setStrategy(new Leo1ConcreteStrategy());
3337console . log ( context . doSomething ( 10 ) )
3438
3539context . setStrategy ( new Leo2ConcreteStrategy ( ) ) ;
36- console . log ( context . doSomething ( 100 ) )
40+ console . log ( context . doSomething ( 100 ) )
41+
42+ /**
43+ * DEMO2
44+ */
45+ interface Strategy {
46+ authenticate ( ...args : any ) : any ;
47+ }
48+
49+ class Authenticator {
50+ strategy : any ;
51+ constructor ( ) {
52+ this . strategy = null ;
53+ }
54+
55+ setStrategy ( strategy : any ) {
56+ this . strategy = strategy ;
57+ }
58+
59+ authenticate ( ...args : any ) {
60+ if ( ! this . strategy ) {
61+ console . log ( '尚未设置认证策略' ) ;
62+ return ;
63+ }
64+ return this . strategy . authenticate ( ...args ) ;
65+ }
66+ }
67+
68+ class WechatStrategy implements Strategy {
69+ authenticate ( wechatToken : string ) {
70+ if ( wechatToken !== '123' ) {
71+ console . log ( '无效的微信用户' ) ;
72+ return ;
73+ }
74+ console . log ( '微信认证成功' ) ;
75+ }
76+ }
77+
78+ class LocalStrategy implements Strategy {
79+ authenticate ( username : string , password : string ) {
80+ if ( username !== 'abao' && password !== '123' ) {
81+ console . log ( '账号或密码错误' ) ;
82+ return ;
83+ }
84+ console . log ( '账号和密码认证成功' ) ;
85+ }
86+ }
87+
88+ const auth = new Authenticator ( ) ;
89+
90+ auth . setStrategy ( new WechatStrategy ( ) ) ;
91+ auth . authenticate ( '123456' ) ;
92+
93+ auth . setStrategy ( new LocalStrategy ( ) ) ;
94+ auth . authenticate ( 'abao' , '123' ) ;
0 commit comments