1. 程式人生 > >設計模式——策略模式

設計模式——策略模式

contex mas bob listbox inf items 收銀系統 setter .com

聲明:以下內容來源於《大話設計模式》,學習。

策略模式:定義了算法家族,分別封裝起來,讓它們之間可以互相替換,此模式讓算法的變化,不會影響到使用算法的客戶。

商場收費策略:正常收費、打折收費、返利收費。

類圖如下:

技術分享

代碼:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Navigation; using System.Windows.Shapes; namespace 策略模式 { /// <summary> /// MainWindow.xaml 的交互邏輯 /// </summary> public partial class MainWindow : Window {
private double moneyTotal = 0d; public MainWindow() { InitializeComponent(); this.cmbType.ItemsSource = Methods.MoneyMethods; this.cmbType.SelectedIndex = 0; } /// <summary> /// 確定 /// </summary> /// <param name="sender"></param>
/// <param name="e"></param> private void Button_Click_1(object sender, RoutedEventArgs e) { CashContext cs = null; switch (cmbType.SelectedItem.ToString()) { case Methods.CON_NORMAL: cs = new CashContext(new CasthNormal()); break; case Methods.CON_REBATE: cs = new CashContext( new CashRebate("0.8")); break; case Methods.CON_RETURN: cs = new CashContext( new CashReturn(300, 30)); break; } double curTotalPrices = 0d; curTotalPrices = cs.GetResult(double.Parse(txtPrice.Text.Trim()) * double.Parse(txtNum.Text.Trim())); moneyTotal += curTotalPrices; lstboxDetail.Items.Add("單價:"+txtPrice.Text.Trim()+"數量:"+txtNum.Text.Trim()+" "+cmbType.SelectedItem.ToString()+ "合計:"+curTotalPrices); txtTotal.Text = moneyTotal.ToString(); } /// <summary> /// 重置 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void Button_Click_2(object sender, RoutedEventArgs e) { lstboxDetail.Items.Clear(); txtPrice.Text = string.Empty; txtNum.Text = string.Empty; txtTotal.Text = "0"; moneyTotal = 0d; } } #region 策略模式 /// <summary> /// 抽象算法類 /// </summary> public abstract class Strategy { public abstract double AcceptCash(double money); } /// <summary> /// 正常收費子類 /// </summary> public class CasthNormal : Strategy { public override double AcceptCash(double money) { return money; } } /// <summary> /// 打折收費子類 /// </summary> public class CashRebate : Strategy { private double reBate = 1d; public CashRebate(string moneyRebate) { reBate = double.Parse(moneyRebate); } public override double AcceptCash(double money) { return money * reBate; } } /// <summary> /// 返利子類 /// </summary> public class CashReturn : Strategy { private double moneyCondition = 0d; private double moneyReturn = 0d; public CashReturn(double moneyConditon,double moneyReturn) { this.moneyCondition = moneyConditon; this.moneyReturn = moneyReturn; } public override double AcceptCash(double money) { double moneyResult = money; if (money >= this.moneyCondition) { moneyResult = money - Math.Floor(money / moneyCondition) * moneyReturn; } return moneyResult; } } public class CashContext { private Strategy cs; public CashContext(Strategy cs) { this.cs = cs; } public double GetResult(double money) { return cs.AcceptCash(money); } } #endregion }
<Window x:Class="策略模式.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="商場收銀系統" Height="350" Width="525">
    <Window.Resources>        
        <ResourceDictionary>
            <ResourceDictionary.MergedDictionaries>
                <ResourceDictionary Source="DicUI.xaml">                    
                </ResourceDictionary>
            </ResourceDictionary.MergedDictionaries>
            <Style  TargetType="StackPanel">
                <Setter Property="Orientation" Value="Horizontal"></Setter>
                <Setter Property="Margin" Value="10"></Setter>
            </Style>
        </ResourceDictionary>
    </Window.Resources>
    <Grid>
        <Grid.RowDefinitions>
            <RowDefinition></RowDefinition>
            <RowDefinition></RowDefinition>
            <RowDefinition></RowDefinition>
            <RowDefinition></RowDefinition>
            <RowDefinition></RowDefinition>
        </Grid.RowDefinitions>
        <Grid.ColumnDefinitions>
            <ColumnDefinition></ColumnDefinition>
        </Grid.ColumnDefinitions>
        <StackPanel Grid.Row="0">
            <TextBlock Style="{StaticResource textBlockStyle}">單價:</TextBlock>
            <TextBox x:Name="txtPrice" Style="{StaticResource textboxStyle}"></TextBox>
            <Button Height="{Binding ElementName=txtPrice, Path=Height}" 
                    Width="75"
                    Click="Button_Click_1"
                    >確定</Button>
        </StackPanel>
        <StackPanel Grid.Row="1">
            <TextBlock Style="{StaticResource textBlockStyle}">數量:</TextBlock>
            <TextBox x:Name="txtNum" Style="{StaticResource textboxStyle}"></TextBox>
            <Button Height="{Binding ElementName=txtPrice, Path=Height}" 
                    Width="75"
                    Click="Button_Click_2"
                    >重置</Button>
        </StackPanel>
        <StackPanel Grid.Row="2">
            <TextBlock Style="{StaticResource textBlockStyle}">計算方式:</TextBlock>
            <ComboBox x:Name="cmbType" Height="{Binding ElementName=txtPrice, Path=Height}" Width="{Binding ElementName=txtPrice, Path=Width}"></ComboBox>
        </StackPanel>
        <ListBox Grid.Row="3" x:Name="lstboxDetail">
            
        </ListBox>
        <Grid Grid.Row="4">
            <Grid>
                <Grid.ColumnDefinitions>
                    <ColumnDefinition Width="Auto"></ColumnDefinition>
                    <ColumnDefinition Width="*"></ColumnDefinition>
                </Grid.ColumnDefinitions>
            <TextBlock Grid.Column="0" Style="{StaticResource textBlockStyle}">總計:</TextBlock>
            <TextBlock Grid.Column="1" Style="{StaticResource textBlockStyle}"
                       HorizontalAlignment="Center"
                       TextAlignment="Center"
                       x:Name="txtTotal"
                       Width="{Binding ElementName=txtPrice, Path=Width}">0</TextBlock>
            </Grid>
        </Grid>
    </Grid>
</Window>



設計模式——策略模式