都说strategy模式可以简化if(){} else if(){}else if(){}....语句
可是在网上找了,感觉这种模式不能简化if(){} else if(){}else if(){}....语句,充其量将复杂的算法封装起来,但是还是要写if(){} else if(){}else if(){}....语句的。 例如 1.if(1==a){
2. //算法1
3.}else if(2 == a){
4. //算法2
5.}else if(3 == a){
6. //算法3
7.} strategy模式的思想是将 算法1 算法2 算法3 分别封装起来,并实现一个 算法接口例如
1.//算法接口
2.public interface Deal{
3. public void request();
4.}
5.
6.//算法1
7.public class S1 implements Deal{
8. public void request(){
9. //算法1
10. };
11.}
12.
13.//算法2
14.public class S2 implements Deal{
15. public void request(){
16. //算法2
17. };
18.}
19.
20.//算法3
21.public class S3 implements Deal{
22. //..... (省略 同算法1算法2)
23.}
还要写一个客户端调用的类
1.public class Execute{
2. private Deal d ;
3. public Execute(Deal d){
4. this.d = d;
5. }
6. public request(){
7. d.request();
8. }
9.} 问题就出来了,在客户端这么调用
1.if( a == 1){
2. Execute exe = new Execute(new S1());
3. exe.request();
4.}else if(a == 2){
5. Execute exe = new Execute(new S2());
6. exe.request();
7.}else if(a == 3){
8. Execute exe = new Execute(new S3());
9. exe.request();
10.} 最终客户端还是要写if ...else语句 我理解的strategy模式就是把复杂的算法给封装起来,但是在客户端还是要用if ...else语句, 我这么理解对么?
可是在网上找了,感觉这种模式不能简化if(){} else if(){}else if(){}....语句,充其量将复杂的算法封装起来,但是还是要写if(){} else if(){}else if(){}....语句的。 例如 1.if(1==a){
2. //算法1
3.}else if(2 == a){
4. //算法2
5.}else if(3 == a){
6. //算法3
7.} strategy模式的思想是将 算法1 算法2 算法3 分别封装起来,并实现一个 算法接口例如
1.//算法接口
2.public interface Deal{
3. public void request();
4.}
5.
6.//算法1
7.public class S1 implements Deal{
8. public void request(){
9. //算法1
10. };
11.}
12.
13.//算法2
14.public class S2 implements Deal{
15. public void request(){
16. //算法2
17. };
18.}
19.
20.//算法3
21.public class S3 implements Deal{
22. //..... (省略 同算法1算法2)
23.}
还要写一个客户端调用的类
1.public class Execute{
2. private Deal d ;
3. public Execute(Deal d){
4. this.d = d;
5. }
6. public request(){
7. d.request();
8. }
9.} 问题就出来了,在客户端这么调用
1.if( a == 1){
2. Execute exe = new Execute(new S1());
3. exe.request();
4.}else if(a == 2){
5. Execute exe = new Execute(new S2());
6. exe.request();
7.}else if(a == 3){
8. Execute exe = new Execute(new S3());
9. exe.request();
10.} 最终客户端还是要写if ...else语句 我理解的strategy模式就是把复杂的算法给封装起来,但是在客户端还是要用if ...else语句, 我这么理解对么?
当算法经常变化或经常变化引用哪个算法,这时可以用strategy。如果楼主if else情况比较固定,算法又稳定,不用strategy,就直接if else判断条件选择算法就可以了。不适当的使用模式会造成代码结构复杂,代码总量增加。