Core Design Patterns(14) State 状态模式

VS 2008

    应应用程序中,常常会有这样一些有状态的对象,它们可能有很多种状态,在不同状态下,对象表现出的行为截然不同。在一般情况下,我们可能会写一些状态切换的if .. else ..语句块,往往造成代码丑陋,维护困难。
    这时候,可以考虑使用状态模式。

1. 模式UML图




2. 应用

    现在程序中需要频繁造作一类对象,我们称之为案件(Task),一个案件的生命周期是一个流程,从受理、派遣、处理、到最终完成,经历四种状态(其实还有更多,这里为了示例,我把它简化了)。因此很容易想到使用状态模式。
    静态类图:



    现在来看代码,Very simple

Task.cs

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

namespace DesignPattern.State.BLL {
    
public class Task {

        
/// <summary>
        
/// 案件唯一编号
        
/// </summary>

        public string TaskId getset; }

        
/// <summary>
        
/// 状态
        
/// </summary>

        public ITaskState State {get;set;}

        
public Task(string taskId, ITaskState state) {
            
this.TaskId = taskId;
            
this.State = state;
        }


        
public void Execute() {
            
this.State.Execute(this);
        }

    }

}


ITaskState.cs

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

namespace DesignPattern.State.BLL {
    
public interface ITaskState {

        
void Execute(Task task);
    }

}


AcceptingState.cs

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

namespace DesignPattern.State.BLL {
    
public class AcceptingState : ITaskState {

        
ITaskState Members
    }

}


DispatchingState.cs

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

namespace DesignPattern.State.BLL {
    
public class DispatchingState : ITaskState {
        
ITaskState Members
    }

}


SolvingState.cs

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

namespace DesignPattern.State.BLL {
    
public class SolvingState : ITaskState {
        
ITaskState Members
    }

}


FinishedState.cs

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

namespace DesignPattern.State.BLL {
    
public class FinishedState : ITaskState {
        
ITaskState Members
    }

}


Client

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using DesignPattern.State.BLL;

namespace DesignPattern.State {
    
class Program {
        
static void Main(string[] args) {

            Task t 
= new Task("0803A0007007"new AcceptingState());
            t.Execute();
            t.Execute();
            t.Execute();
            t.Execute();
        }

    }

}


Output

posted on 2008-03-20 20:05  Tristan(GuoZhijian)  阅读(2790)  评论(8编辑  收藏  举报