策略模式
推荐一个讲解设计模式的网站
点击进入
https://refactoringguru.cn/design-patterns/catalog
案例
使用的App大多都有分享的功能,我们可以选择分享到不同的地方,比如微博、微信、QQ等等,虽然是同一个内容,但是分享到不同的平台就会有不同的处理方式
实现方式:
a) 提供公共接口或抽象类,定义需要使用的策略方法。(策略抽象类)
b) 多个实现的策略抽象类的实现类。(策略实现类)
c) 环境类,对多个实现类的封装,提供接口类型的成员量,可以在客户端中切换。
d) 客户端 调用环境类 进行不同策略的切换。
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace strategyDemo
{
class Program
{
static void Main(string[] args)
{
new Program().shareOptions("Sina");
Console.ReadLine();
}
//(策略抽象类)定义策略接口
public interface DealStrategy
{
void dealMythod(String option);
}
//(策略实现类)定义具体的策略1
public class DealSina : DealStrategy
{
public void dealMythod(string option)
{
Console.WriteLine("Sina");
}
}
//(策略实现类)定义具体的策略2
public class DealWeChat : DealStrategy
{
public void dealMythod(string option)
{
Console.WriteLine("WeChat");
}
}
//(策略实现类)定义具体的策略3
//.............
//(环境类)对多个实现类的封装,提供接口类型的成员量,可以在客户端中切换
public class DealContext
{
//属性
public String type;
public DealStrategy deal;
//构造器
public DealContext(String type, DealStrategy deal)
{
this.type = type;
this.deal = deal;
}
//方法
public DealStrategy getDeal()
{
return deal;
}
public Boolean options (String type)
{
return this.type.Equals(type);
}
}
public class Share
{
//加载所有的策略
public static List<DealContext> getAllStrategy()
{
List<DealContext> algs = new List<DealContext> ();
algs.Add(new DealContext("Sina",new DealSina()));
algs.Add(new DealContext("WeChat",new DealWeChat()));
return algs;
}
}
//(客户端)调用环境类 进行不同策略的切换
public void shareOptions(String type)
{
DealStrategy dealStrategy = null;
foreach (DealContext deal in Share.getAllStrategy())
{
if (deal.options(type)) {
dealStrategy = deal.getDeal();
break;
}
}
dealStrategy.dealMythod(type);
}
}
}
使用策略模式后,去除了if…else这样的条件判断语句,代码的可维护性和可拓展性得到提高