设计模式(二)之策略模式

简介: 策略模式:定义了算法家族,分别封装起来,让其之间可以互相替换,此模式让算法的变化,不会影响到使用算法的客户。

QQ图片20220424000423.jpg

策略模式:定义了算法家族,分别封装起来,让其之间可以互相替换,此模式让算法的变化,不会影响到使用算法的客户。


下边使用例子来具体分析:


制作一个商场收银的软件,营业员根据客户购买的单价和数量,向客户收费。并附带打折的选项。效果如下图所示:


QQ图片20220424000420.jpg


主要部分代码:


using System;
using System.Windows.Forms;
namespace strategy
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
        private void Form1_Load(object sender, EventArgs e)
        {
            comboBox1.Items.Add("8折");
            comboBox1.Items.Add("6折");
            comboBox1.Items.Add("4折");
        }
        /// <summary>
        /// 单价
        /// </summary>
        public double price;
        /// <summary>
        /// 数量
        /// </summary>
        public double number;
        /// <summary>
        /// 总价钱
        /// </summary>
        public double total;
        /// <summary>
        /// 确定按钮点击事件
        /// </summary>
        private void button1_Click(object sender, EventArgs e)
        {
            Console.WriteLine(comboBox1);
            price = Convert.ToDouble(textBox1.Text);
            number = Convert.ToDouble(textBox2.Text);
            switch (comboBox1.SelectedIndex)
            {
                case 0:
                    total = price * number * 0.8;
                    break;
                case 1:
                    total = price * number * 0.6;
                    break;
                case 2:
                    total = price * number * 0.4;
                    break;
                default:
                    total = price * number;
                    break;
            }
            richTextBox1.Text = Convert.ToString(total);
            label5.Text = Convert.ToString(total);
        }
        /// <summary>
        /// 重置按钮点击事件
        /// </summary>
        private void button2_Click(object sender, EventArgs e)
        {
            textBox1.Clear();
            textBox2.Clear();
            richTextBox1.Clear();
            label5.Text = "";
        }
    }
}


这样就可以实现上边所描述的功能。


这个例子我们也可以使用简单工厂模式来实现。刚好也复习一下“简单工厂模式”。

简单工厂模式的精髓就是在基类(abstract,interface ,class)中定义一个方法,由其子类来实现或者重写他。将逻辑计算部分封装成一个工厂类,工厂类只返回对应的子类的对象。再有这个对象调用其下的方法。


Form1.cs:


using System;
using System.Windows.Forms;
namespace strategy
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
        private void Form1_Load(object sender, EventArgs e)
        {
            comboBox1.Items.Add("8折");
            comboBox1.Items.Add("6折");
            comboBox1.Items.Add("4折");
        }
        /// <summary>
        /// 单价
        /// </summary>
        public double price;
        /// <summary>
        /// 数量
        /// </summary>
        public double number;
        /// <summary>
        /// 总价钱
        /// </summary>
        public double total;
        /// <summary>
        /// 确定按钮点击事件
        /// </summary>
        private void button1_Click(object sender, EventArgs e)
        {
            Total tooo = null;
            price = Convert.ToDouble(textBox1.Text);
            number = Convert.ToDouble(textBox2.Text);
            int count = comboBox1.SelectedIndex;
            Reckon reckon = new Reckon();
            tooo = reckon.PutOut(count);
            total = tooo.getResult(price, number);
            richTextBox1.Text = Convert.ToString(total);
            label5.Text = Convert.ToString(total);
        }
        /// <summary>
        /// 重置按钮点击事件
        /// </summary>
        private void button2_Click(object sender, EventArgs e)
        {
            textBox1.Clear();
            textBox2.Clear();
            richTextBox1.Clear();
            label5.Text = "";
        }
    }
}


抽象类:


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace strategy
{
    public abstract class Total
    {
        public abstract double getResult(double price, double number);
    }
}


工厂类:


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace strategy
{
    /// <summary>
    /// 计算类
    /// </summary>
    public class Reckon
    {
        public Total tooo = null;
        /// <summary>
        /// 总价钱
        /// </summary>
        public double total;
        public Total PutOut(int count)
        {
            switch (count)
            {
                case 2:
                    tooo = new Four();
                    break;
                case 1:
                    tooo = new Six() ;
                    break;
                case 0:
                    tooo = new Eight();
                    break;
                default:
                    tooo = new Normal();
                    break;
            }
            return tooo;
        }
    }
}


子类:


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace strategy
{
    public class Four:Total
    {
        public override double getResult(double price, double number)
        {
            double total;
            total = price * number * 0.8;
            return total;
        }
    }
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace strategy
{
    public class Six:Total
    {
        public override double getResult(double price, double number)
        {
            double total;
            total = price * number * 0.6;
            return total;
        }
    }
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace strategy
{
    public class Eight:Total
    {
        public override double getResult(double price, double number)
        {
            double total;
            total = price * number * 0.8;
            return total;
        }
    }
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace strategy
{
    public class Normal:Total
    {
        public override double getResult(double price, double number)
        {
            double total;
            total = price * number;
            return total;
        }
    }
}


以上是用简单工厂模式来实现的这个例子。


这里介绍的是策略模式,所以使用简单工厂模式实现的不是我们想要的,因为每一次我修改结构,添加新的打折策略都需要修改工厂类和添加新的算法类。


策略模式:定义了算法家族,分别封装起来。让其之间可以互相替换,此模式让算法的变化,不会影响到使用这个算法的用户。以上是官方给的说法。


策略模式和简单工厂模式区别:


简单工厂模式是直接返回你需要的算法的对象。再使用对象进行操作


策略模式加了一层,调用策略类,传你需要的算法类对象,直接返回你需要的到的数值。


上代码:

Form1.cs


using System;
using System.Windows.Forms;
namespace strategy
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
        private void Form1_Load(object sender, EventArgs e)
        {
            comboBox1.Items.Add("8折");
            comboBox1.Items.Add("6折");
            comboBox1.Items.Add("4折");
        }
        /// <summary>
        /// 单价
        /// </summary>
        public double price;
        /// <summary>
        /// 数量
        /// </summary>
        public double number;
        /// <summary>
        /// 总价钱
        /// </summary>
        public double total;
        public CeLue celue;
        /// <summary>
        /// 确定按钮点击事件
        /// </summary>
        private void button1_Click(object sender, EventArgs e)
        {
            Total tooo = null;
            if (textBox1.Text == "")
            {
                return;
            }
            price = Convert.ToDouble(textBox1.Text);
            number = Convert.ToDouble(textBox2.Text);
            int count = comboBox1.SelectedIndex;
            switch (count)
            {
                case 2:
                    celue = new CeLue(new Four(),price,number);
                    break;
                case 1:
                    celue = new CeLue(new Six(),price,number);
                    break;
                case 0:
                    celue = new CeLue(new Eight(), price, number);
                    break;
                default:
                    celue = new CeLue(new Normal(), price, number);
                    break;
            }
            // 调用
            total = celue.getCeLue();
            //Reckon reckon = new Reckon();
            //tooo = reckon.PutOut(count);
            //total = tooo.getResult(price, number);
            richTextBox1.Text = Convert.ToString(total);
            label5.Text = Convert.ToString(total);
        }
        /// <summary>
        /// 重置按钮点击事件
        /// </summary>
        private void button2_Click(object sender, EventArgs e)
        {
            textBox1.Clear();
            textBox2.Clear();
            richTextBox1.Clear();
            label5.Text = "";
        }
    }
}


CeLue.cs


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace strategy
{
    /// <summary>
    /// 策略类
    /// </summary>
    public class CeLue
    {
        public Total total;
        public double pri;
        public double num;
        public double to;
        public CeLue(Total tooo,double price,double number)
        {
            total = tooo;
            pri = price;
            num = number;
        }
        public double getCeLue()
        {
            to = total.getResult(pri, num);
            return to;
        }
    }
}


基类:Total.cs


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace strategy
{
    public abstract class Total
    {
        public abstract double getResult(double price, double number);
    }
}


算法类:


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace strategy
{
    public class Six:Total
    {
        public override double getResult(double price, double number)
        {
            double total;
            total = price * number * 0.6;
            return total;
        }
    }
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace strategy
{
    public class Four:Total
    {
        public override double getResult(double price, double number)
        {
            double total;
            total = price * number * 0.8;
            return total;
        }
    }
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace strategy
{
    public class Eight:Total
    {
        public override double getResult(double price, double number)
        {
            double total;
            total = price * number * 0.8;
            return total;
        }
    }
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace strategy
{
    public class Normal:Total
    {
        public override double getResult(double price, double number)
        {
            double total;
            total = price * number;
            return total;
        }
    }
}


对比一下简单工厂模式和策略模式发现,单纯的使用策略模式,对算法的封装确实更科学了一些。但是在调用的时候,我们又回到了之前的模样,在客户端判断到底是哪一个算法,这个时候,我们可以将策略模式与简单工厂模式结合使用。

将判断算法部分放到策略类的构造函数中。代码如下所示:


Form1.cs


using System;
using System.Windows.Forms;
namespace strategy
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
        private void Form1_Load(object sender, EventArgs e)
        {
            comboBox1.Items.Add("8折");
            comboBox1.Items.Add("6折");
            comboBox1.Items.Add("4折");
        }
        /// <summary>
        /// 单价
        /// </summary>
        public double price;
        /// <summary>
        /// 数量
        /// </summary>
        public double number;
        /// <summary>
        /// 总价钱
        /// </summary>
        public double total;
        public CeLue celue;
        /// <summary>
        /// 确定按钮点击事件
        /// </summary>
        private void button1_Click(object sender, EventArgs e)
        {
            Total tooo = null;
            if (textBox1.Text == "")
            {
                return;
            }
            price = Convert.ToDouble(textBox1.Text);
            number = Convert.ToDouble(textBox2.Text);
            int count = comboBox1.SelectedIndex;
            CeLue celue = new CeLue(price, number, count);
            // 调用
            total = celue.getCeLue();
            //Reckon reckon = new Reckon();
            //tooo = reckon.PutOut(count);
            //total = tooo.getResult(price, number);
            richTextBox1.Text = Convert.ToString(total);
            label5.Text = Convert.ToString(total);
        }
        /// <summary>
        /// 重置按钮点击事件
        /// </summary>
        private void button2_Click(object sender, EventArgs e)
        {
            textBox1.Clear();
            textBox2.Clear();
            richTextBox1.Clear();
            label5.Text = "";
        }
    }
}


策略模式和简单工厂模式结合:


CeLue.cs


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace strategy
{
    /// <summary>
    /// 策略类
    /// </summary>
    public class CeLue
    {
        public Total total;
        public double pri;
        public double num;
        public double to;
        public CeLue(double price,double number,int count)
        {
            pri = price;
            num = number;
            switch (count)
            {
                case 2:
                    total = new Four();
                    break;
                case 1:
                    total = new Six();
                    break;
                case 0:
                    total = new Eight();
                    break;
                default:
                    total = new Normal();
                    break;
            }
        }
        public double getCeLue()
        {
            to = total.getResult(pri, num);
            return to;
        }
    }
}


其余代码没有改变。


这个就是策略模式,按照官方的说法就是算法的家族。让算法的变化,不会影响到使用算法的用户。



目录
相关文章
|
2月前
|
设计模式 算法 搜索推荐
Java 设计模式之策略模式:灵活切换算法的艺术
策略模式通过封装不同算法并实现灵活切换,将算法与使用解耦。以支付为例,微信、支付宝等支付方式作为独立策略,购物车根据选择调用对应支付逻辑,提升代码可维护性与扩展性,避免冗长条件判断,符合开闭原则。
295 35
|
3月前
|
设计模式 人工智能 算法
基于多设计模式的状态扭转设计:策略模式与责任链模式的实战应用
接下来,我会结合实战案例,聊聊如何用「策略模式 + 责任链模式」构建灵活可扩展的状态引擎,让抽奖系统的状态管理从「混乱战场」变成「有序流水线」。
|
7月前
|
设计模式 算法 Java
设计模式觉醒系列(04)策略模式|简单工厂模式的升级版
本文介绍了简单工厂模式与策略模式的概念及其融合实践。简单工厂模式用于对象创建,通过隐藏实现细节简化代码;策略模式关注行为封装与切换,支持动态替换算法,增强灵活性。两者结合形成“策略工厂”,既简化对象创建又保持低耦合。文章通过支付案例演示了模式的应用,并强调实际开发中应根据需求选择合适的设计模式,避免生搬硬套。最后推荐了JVM调优、并发编程等技术专题,助力开发者提升技能。
|
设计模式 算法 Kotlin
Kotlin - 改良设计模式 - 策略模式
Kotlin - 改良设计模式 - 策略模式
142 4
|
7月前
|
设计模式 算法 搜索推荐
【设计模式】【行为型模式】策略模式(Strategy)
一、入门 什么是策略模式? 策略模式是一种行为设计模式,允许在运行时选择算法或行为。它将算法封装在独立的类中,使得它们可以互换,而不影响客户端代码。 为什么需要策略模式? 策略模式的主要目的是解决算法
141 14
|
10月前
|
设计模式 算法 开发者
「全网最细 + 实战源码案例」设计模式——策略模式
策略模式(Strategy Pattern)是一种行为型设计模式,用于定义一系列可替换的算法或行为,并将它们封装成独立的类。通过上下文持有策略对象,在运行时动态切换算法,提高代码的可维护性和扩展性。适用于需要动态切换算法、避免条件语句、经常扩展算法或保持算法独立性的场景。优点包括符合开闭原则、运行时切换算法、解耦上下文与策略实现、减少条件判断;缺点是增加类数量和策略切换成本。示例中通过定义抽象策略接口和具体策略类,结合上下文类实现动态算法选择。
331 8
「全网最细 + 实战源码案例」设计模式——策略模式
|
12月前
|
设计模式 存储 缓存
前端必须掌握的设计模式——策略模式
策略模式(Strategy Pattern)是一种行为型设计模式,旨在将多分支复杂逻辑解耦。每个分支类只关心自身实现,无需处理策略切换。它避免了大量if-else或switch-case代码,符合开闭原则。常见应用场景包括表单验证、风格切换和缓存调度等。通过定义接口和上下文类,策略模式实现了灵活的逻辑分离与扩展。例如,在国际化需求中,可根据语言切换不同的词条包,使代码更加简洁优雅。总结来说,策略模式简化了多条件判断,提升了代码的可维护性和扩展性。
|
设计模式 算法 Kotlin
Kotlin教程笔记(53) - 改良设计模式 - 策略模式
Kotlin教程笔记(53) - 改良设计模式 - 策略模式
136 1
|
设计模式 前端开发 JavaScript
JavaScript设计模式及其在实战中的应用,涵盖单例、工厂、观察者、装饰器和策略模式
本文深入探讨了JavaScript设计模式及其在实战中的应用,涵盖单例、工厂、观察者、装饰器和策略模式,结合电商网站案例,展示了设计模式如何提升代码的可维护性、扩展性和可读性,强调了其在前端开发中的重要性。
178 2
|
设计模式 算法 Kotlin
Kotlin教程笔记(53) - 改良设计模式 - 策略模式
Kotlin教程笔记(53) - 改良设计模式 - 策略模式
105 2

热门文章

最新文章