State Pattern, 主要作用在流程的狀態判斷, 有時候為了處理不同的狀態會透過switch case 或是
if else去判斷的所有的狀態值, 此時會造成程式太過於冗長, 就需要透過一些設計的方式來重新建構
例:我要去銀行辦信用卡, 需要寫一張申請單, 然後經過核可, 最後是申請結束.
以下範例為C#

A.首先創建一個委派用的抽像類別, state
    public abstract class state
    {
        public abstract void nextStates(flw flows);
    }

B.再創建流程動作

    public class flw
    {
        private state states;
        public flw()
        {
            states = new StartStates();
        }
        public void nextState()
        {
            states.nextStates(this);
        }
        public void setState(state state)
        {
            this.states = state;
        }
    }
    

C.每個流程的階段內容

    public class StartStates : state //開始階段
    {
        public override void nextStates(flw flows)
        {
            flows.setState(new ApplyStates()); //將階段任務給至下一個階段
            Console.WriteLine("提出申請");
        }
    }
    public class ApplyStates : state //審核階段
    {
        public override void nextStates(flw flows)
        {
            flows.setState(new HRState());
            Console.WriteLine("Check Process");
        }
    }

    public class HRState : state //處理階段
    {
        public override void nextStates(flw flows)
        {
            flows.setState(new stopStates());
            Console.WriteLine("結束流程");
            
        }
    }

    public class stopStates: state //最後結束的階段
    {
        public override void nextStates(flw flows)
        {          
            Console.WriteLine("結束流程");            
        }
    }


範例2 : 透過delegation C#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace DelegateAP

{
    public class delegateNts
    {
        public delegate void ssN();
    }

    public class flw :delegateNts
    {
        public flw()
        {        }
        public void BusinessStepWork()
        {
          StartStates sstepBy= new StartStates ();
          ssN NextSates ;
          NextSates = sstepBy.nextStates;
          NextSates += sstepBy.ApplyStatus;
          NextSates += sstepBy.EndStatus;
          NextSates.Invoke();
        }
    }
    public class StartStates
    {
        public  void nextStates()
        {
            Console.WriteLine("提出申請");
        }
        public  void ApplyStatus()
        {
            Console.WriteLine("Check Process");
        }
        public  void EndStatus()
        {
            Console.WriteLine("結束流程");
        }
        public  void OverStatus()
        {
            Console.WriteLine("end less");
        }
    }

}





arrow
arrow

    斷了線的小木偶 發表在 痞客邦 留言(0) 人氣()