策略是为达到某一目的而采取的手段或方法,策略模式的本质是目标与手段的分离,手段不同而最终达成的目标一致。客户只关心目标而不在意具体的实现方法,实现方法要根据具体的环境因素而变化。
// 上传附件策略
public abstract class Strategy
{
// 上传附件
public abstract void UpLoad();
}
// 使用阿里云的策略
public class AliYunStrategy : Strategy
{
public override void UpLoad()
{
Console.WriteLine("我把数据存到了阿里云!");
}
}
// 本地策略
public class LocalStrategy : Strategy
{
public override void UpLoad()
{
Console.WriteLine("我把数据存到了本地文件夹!");
}
}
public class MongoDbStrategy : Strategy {
public override void UpLoad()
{
Console.WriteLine("我把数据存到了芒果数据库!");
}
}
public class Context
{
private Strategy _strategy;
public Context(Strategy strategy) {
_strategy = strategy;
}
public void UploadFile() {
_strategy.UpLoad();
}
}
static void Main(string[] args)
{
new Context(new AliYunStrategy()).UploadFile();
new Context(new LocalStrategy()).UploadFile();
new Context(new MongoDbStrategy()).UploadFile();
Console.ReadLine();
}