首页 > 编程语言 >C#设计模式之策略模式

C#设计模式之策略模式

时间:2022-12-18 20:46:19浏览次数:61  
标签:GetPrice 策略 C# System 模式 上下文 using originPrice 设计模式

原文链接:https://www.jb51.net/article/239469.htm

策略模式

所谓策略其实就是做一件事情有很多很多的方法。

比如说一个商场要搞促销,促销的方式有可能有很多:打折啊,满100返50啊、积分等等之类的。

这种不同的促销方式在我们系统中表示就是一个一个的策略,并且策略是可以随时更换的,这个时候在设计系统时就可以使用策略模式
商场有可能会更换或追加新的促销模式,也就是策略存在调整,也就是会更改以前的代码,为了满足开闭原则,这时就要使用抽象类和接口,这里我们偏向使用接口。

在接口里面定义策略的方法,根据不同的情况编写不同的实现类,实现不同的策略,策略模式比较适用于算法经常变化的情况。比如计算工资的方式出行方式的选择等等。

1、开闭原则(Open Close Principle)

开闭原则的意思是:

对扩展开放,对修改关闭

在程序需要进行拓展的时候,不能去修改原有的代码,实现一个热插拔的效果。

简言之,是为了使程序的扩展性好,易于维护和升级。

想要达到这样的效果,我们需要使用接口抽象类,后面的具体设计中我们会提到这点。

 如图所示,我们先定义策略的接口(Promotion),然后在这个策略接口里定义策略的方法(GetPrice()),接着我们定义了两种具体的策略(Discount打折)和(MoneyBack返现)。
策略模式会专门有一个上下文对象(PromotionContext)专门管理策略类,并且上下文对象和策略接口之间是聚合的关系,也就是整体和部分的关系,因此在上下文对象里应该保存一个促销类型的引用,另外上下文对象里一般会有一些方便客户端调用的方法,如GetPrice()。

客户端程序可以通过上下文对象得到价格,这个GetPrice()里会根据不同的策略,执行不同的策略方法。
如果客户端不想使用上下文中定义的默认的策略,也可以去修改策略类,因为上下文中有一个ChangePromotion()的方法,客户端主要使用上下文对象,如果需要修改策略,他还要依赖于具体的策略对象。

示例:

1、策略接口:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace 策略模式
{
    /*
       策略接口
     */
    public interface IPromotion
    {
        /// <summary>
        /// 根据原价和策略计算新价格
        /// </summary>
        /// <param name="originPrice">原价</param>
        /// <returns></returns>
        double GetPrice(double originPrice);
    }
}

2、Discount打折策略类

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace 策略模式
{
    /// <summary>
    /// 打折策略类
    /// </summary>
   public  class Discount :IPromotion
    {

        public double GetPrice(double originPrice)
        {
            Console.WriteLine("打八折:");
            return originPrice * 0.8;
        }
    }
}

3、MoneyBack返现类

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace 策略模式
{
    /*
     返现策略类:满100返50的策略
     */
    class MoneyBack :IPromotion
    {
        public double GetPrice(double originPrice)
        {
            Console.WriteLine("满100返50");
            return originPrice - (int)originPrice / 100 * 50;
        }
    }
}

4、策略上下文类

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace 策略模式
{
    /*
     策略上下文,为客户选择合适的策略
     */
   public  class PromotionContext
    {
       private IPromotion p = null;

       public PromotionContext(IPromotion p)
       {
           this.p = p;
       }

       public double GetPrice(double originPrice)
       {
           // 默认策略
           if (this.p == null)
           {
               this.p = new Discount();
           }
           return this.p.GetPrice(originPrice);
       }

       /// <summary>
       /// 更改策略的方法
       /// </summary>
       /// <param name="p"></param>
       public void ChangePromotion(IPromotion p)
       {
           this.p = p;
       }
    }
}

5、主程序调用

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace 策略模式
{
    class Program
    {
        static void Main(string[] args)
        {
            // 默认策略:打八折的策略
            PromotionContext pc = new PromotionContext(null);
            Console.WriteLine(pc.GetPrice(200)) ;

            // 更改策略:满100返50的策略
            pc.ChangePromotion(new MoneyBack());
            Console.WriteLine(pc.GetPrice(155.9));
            Console.ReadKey();
        }
    }
}

代码下载地址:点击下载

 

标签:GetPrice,策略,C#,System,模式,上下文,using,originPrice,设计模式
From: https://www.cnblogs.com/zhu4c4/p/16990881.html

相关文章

  • PyTorch中利用LSTMCell搭建多层LSTM实现时间序列预测
    OverridetheentrypointofanimageIntroducedinGitLabandGitLabRunner9.4.Readmoreaboutthe extendedconfigurationoptions.Beforeexplainingtheav......
  • 如何不在main函数中访问Qapplication
    在学习qt的过程中,我们会慢慢的将主要代码在main函数外开发,这时可能会遇见不知道如何访问Qapplication的情况。比如,我们创建了MyWidget类,并在其中添加了一个按钮,我们希望按......
  • C#实现简单的异或加密,方便处理
    将本地的mp4和ts文件加密为“dj”文件,无法播放。解密则是将“dj”文件解密为mp4或ts文件。usingSystem;usingSystem.Collections.Generic;usingSystem.IO;usingSy......
  • DNS用的是TCP协议还是UDP协议
    DNS占用53号端口,同时使用TCP和UDP协议。那么DNS在什么情况下使用这两种协议?DNS在区域传输的时候使用TCP协议,其他时候使用UDP协议。(一)TCP与UDP简介TCP---传输控制协议,是......
  • (摘抄)Defining Application Servers in IntelliJ IDEA
     ThisfeatureissupportedintheUltimateeditiononly.TodefineaserverinIntelliJIDEA,inmostofthecases,allyouhavetodoistospecifywherethec......
  • (转)logback 常用配置详解(二) <appender>
     logback常用配置详解(二)标签: ​​thread​​​​file​​​​活动​​​​date​​​​logging​​​​正则表达式​​2011-09-2017:21 21632人阅读 ......
  • (转)expect学习笔记及实例详解
    expect学习笔记及实例详解1.expect是基于tcl演变而来的,所以很多语法和tcl类似,基本的语法如下所示:1.1首行加上/usr/bin/expect1.2spawn:后......
  • (转)jmeter 测试webservice
    地址:http://itindex.net/detail/45270-jmeter-webservice-%E6%B5%8B%E8%AF%95 1. BuildingaWebServiceTestPlan参考​​http://jmeter.apache.org/usermanual/build-w......
  • Springmvc构造RESTful详细讲解
    ​​Springmvc构造RESTful详细讲解​​Rest介绍 /blog/1HTTPGET=>得到id=1的blog/blog/1HTTPDELETE......
  • m基于simulink的WCDMA通信链路仿真
    1.算法概述W-CDMA由ETSINTTDoCoMo作为无线介面为他们的3G网路FOMA开发。后来NTTDocomo提交给ITU一个详细规范作为一个象IMT-2000一样作为一个候选的国际3G标准。国际电信......