VS 2008

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

1. 模式UML图


Core Design Patterns(14) State 状态模式

2. 应用

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

Core Design Patterns(14) State 状态模式

    现在来看代码,Very simple

Task.cs

Core Design Patterns(14) State 状态模式using System;
Core Design Patterns(14) State 状态模式
using System.Collections.Generic;
Core Design Patterns(14) State 状态模式
using System.Linq;
Core Design Patterns(14) State 状态模式
using System.Text;
Core Design Patterns(14) State 状态模式

ITaskState.cs

Core Design Patterns(14) State 状态模式using System;
Core Design Patterns(14) State 状态模式
using System.Collections.Generic;
Core Design Patterns(14) State 状态模式
using System.Linq;
Core Design Patterns(14) State 状态模式
using System.Text;
Core Design Patterns(14) State 状态模式

AcceptingState.cs

Core Design Patterns(14) State 状态模式using System;
Core Design Patterns(14) State 状态模式
using System.Collections.Generic;
Core Design Patterns(14) State 状态模式
using System.Linq;
Core Design Patterns(14) State 状态模式
using System.Text;
Core Design Patterns(14) State 状态模式

DispatchingState.cs

Core Design Patterns(14) State 状态模式using System;
Core Design Patterns(14) State 状态模式
using System.Collections.Generic;
Core Design Patterns(14) State 状态模式
using System.Linq;
Core Design Patterns(14) State 状态模式
using System.Text;
Core Design Patterns(14) State 状态模式

SolvingState.cs

Core Design Patterns(14) State 状态模式using System;
Core Design Patterns(14) State 状态模式
using System.Collections.Generic;
Core Design Patterns(14) State 状态模式
using System.Linq;
Core Design Patterns(14) State 状态模式
using System.Text;
Core Design Patterns(14) State 状态模式

FinishedState.cs

Core Design Patterns(14) State 状态模式using System;
Core Design Patterns(14) State 状态模式
using System.Collections.Generic;
Core Design Patterns(14) State 状态模式
using System.Linq;
Core Design Patterns(14) State 状态模式
using System.Text;
Core Design Patterns(14) State 状态模式

Client

Core Design Patterns(14) State 状态模式using System;
Core Design Patterns(14) State 状态模式
using System.Collections.Generic;
Core Design Patterns(14) State 状态模式
using System.Linq;
Core Design Patterns(14) State 状态模式
using System.Text;
Core Design Patterns(14) State 状态模式
using DesignPattern.State.BLL;
Core Design Patterns(14) State 状态模式

Output

Core Design Patterns(14) State 状态模式

相关文章: