设计模式:策略模式(Strategy Design Pattern)

个人觉得学习设计模式的话,还是应该注重各种设计模式的应用场景,23种设计模式真的挺多的,要靠死记硬背的话还是没那么容易记住。所以我建议可以在自己实际编码时,套用上各种设计模式。
策略模式是一个很好的例子,如果需要用到大量的if~else判断的话,就可以用到策略模式
我们使用的app大多都有分享的功能,我们可以选择分享到不同的地方,比如微博、微信、QQ等等,虽然是同一个内容,但是分享到不同的平台就会有不同的处理方式,比如要跳转到不同的app或者直接复制链接等等。如果让你来实现这个功能,你会如何实现呢?
在这里插入图片描述
用了策略模式之前:

public void Share{
    
    
public void shareOptions(String option){
    
    
       if(option.equals("微博")){
    
    
           //function1();
           //...
      }else if(option.equals("微信")){
    
    
           //function2();
           //...
      }else if(option.equals("朋友圈")){
    
    
           //function3();
           //...
      }else if(option.equals("QQ")){
    
    
           //function4();
           //...
      }
       //...
}

这样的话如果以后要修改这些分享方式的话,可读性不够高。
如果我们用上了策略模式:
1.分享方式类:

//定义策略接口
public interface DealStrategy{
    
    
   void dealMythod(String option);
}

//定义具体的策略1
//新浪
public class DealSina implements DealStrategy{
    
    
   @override
   public void dealMythod(String option){
    
    
       //...
  }
}

//定义具体的策略2
//微信
public class DealWeChat implements DealStrategy{
    
    
   @override
   public void dealMythod(String option){
    
    
       //...
  }
}

2.上下文:


//定义上下文,用于使用DealStrategy角色
public static class DealContext{
    
    
   private String type;
   private DealStrategy deal; //分享方式
   
   public  DealContext(String type,DealStrategy deal){
    
    
       this.type = type;
       this.deal = deal;
}
   public getDeal(){
    
    
       return deal;
   }
   public boolean options(String type){
    
    
       return this.type.equals(type);
   }
}

3.share类:

public void Share{
    
    
   private static List<DealContext> algs = new ArrayList();   //静态代码块,先加载所有的策略
   static {
    
    
          	algs.add(new DealContext("Sina",new DealSina()));
          	algs.add(new DealContext("WeChat",new DealWeChat()));
          }
    public void shareOptions(String type){
    
     
          DealStrategy dealStrategy = null;
          for (DealContext deal : algs) {
    
     
 			if (deal.options(type)) {
    
                  
  				dealStrategy = deal.getDeal();        
        		break;       
            	}       
            }      
    dealStrategy.dealMythod(type); 
  }
}

猜你喜欢

转载自blog.csdn.net/weixin_45251189/article/details/109052323