策略模式(strategy)行为型模式c#简单例子

策略模式(strategy)行为型模式c#简单例子

例子主是运用策略模式分解几种移动算法。

namespace adapterpattern
{
    public partial class StrategyFrom : Form
    {
        public StrategyFrom()
        {
            InitializeComponent();
        }

        private void btnDisplay_Click(object sender, EventArgs e)
        {
            Context context1 = new Context(new LeftMove ());
            context1.moveMethod1();
            listBox1.Items.Add(moveData.moveString );
            context1.moveMethod2();
            listBox1.Items.Add(moveData .moveString );
            Context context2= new Context(new RightMove());//算法变动后
            context2.moveMethod1();
            listBox1.Items.Add(moveData.moveString);
            context2.moveMethod2();
            listBox1.Items.Add(moveData.moveString);
           
        }
    }
    public interface IProessMove//表达算法抽象(strategy)
    {
        void Process();
    }
    public class Context
    {
        IProessMove proessMove;//对象组合
        public Context(IProessMove proessMove)//策略模式的连接点
        {
            this.proessMove = proessMove;
        }
        public void moveMethod1()
        {
            proessMove.Process();
            moveData.moveString += "方法1;";
        }
        public void moveMethod2()
        {
           
            proessMove.Process();
            moveData.moveString += "方法2;";
        }
    }
    public class moveData//移动算法中用到数据
    {
        public static  string moveString { set; get; }
    }
    public class LeftMove : IProessMove//移动算法1
    {
          public void Process()
        {
        moveData . moveString = "左移动算法";
        }
    }
    public class RightMove : IProessMove//移动算法2
    {
        public void Process()
        {
           moveData.moveString  = "右移动算法";
        }
    }
    public class TopMove : IProessMove//移动算法3
    {
        public void Process()
        {
          moveData.moveString   = "向上移动算法";
        }
    }
 
}


策略模式(strategy)行为型模式c#简单例子

上一篇:3.关于QT中的MainWindow窗口,MenuBar,ToolBar,QuickTip等方面的知识点


下一篇:C# 类型的创建