NHibernate和State Pattern持久性 - 一个很好的实现?

时间:2010-05-10 14:17:27

标签: c# nhibernate state

以下是我对状态模式的实现。为了使用NHibernate将State对象持久化到我的数据库,我将为每个状态类分配一个枚举值。它作为私有字段存储在实体上,并映射到数据库表中的整数字段。

我想知道这是否是一个很好的实现,因为我将在整个应用程序中使用状态模式,并希望第一次就能正确使用它。感谢

public class Order
{
    private OrderStatusEnum _statusId;
    public virtual Guid Id { get; set; }

    private OrderState _status;
    public virtual OrderState Status {
        get
        {
            if (_status == null)
                _status = GetState(_statusId);
            return _status;
        }
        set
        {
            _status = value;
            _statusId = _status.Id;
        }
    }

    private OrderState GetState(OrderStatusEnum status)
    {
        switch (_statusId) {
            case OrderStatusEnum.Pending:
                return new Submitted(this);
            case OrderStatusEnum.Completed:
                return new Completed(this);
            default:
                return new NewOrder(this);
        }
    }
}

public abstract class OrderState
{
    private readonly Order _order;

    public OrderState(Order order) {
        _order = order;
    }

    internal Order Order { get { return _order; } }
    public abstract OrderStatusEnum Id { get; }

    public virtual void Submit() {
        throw new InvalidOperationException(
            string.Format("Can't Submit a {0} Order", this.GetType().Name)
        );
    }

    public virtual void Complete() {
        throw new InvalidOperationException(
                string.Format(string.Format("Can't Cancel a {0} Order", this.GetType().Name))
            );
    }

    protected internal void _Submit() {
        Order.Status = new Submitted(Order);
    }

    protected internal void _Complete() {
        Order.Status = new Completed(Order);
    }
}

public class NewOrder : OrderState
{
    public NewOrder(Order order) : base(order) { }

    public override OrderStatusEnum Id {
        get { return OrderStatusEnum.New; }
    }

    public override void Submit() {
        _Submit();
    }
}

public class Submitted : OrderState
{
    public Submitted(Order order) : base(order) { }

    public override OrderStatusEnum Id {
        get { return OrderStatusEnum.Pending; }
    }

    public override void Complete() {
        _Complete();
    }
}

public class Completed : OrderState
{
    public Completed(Order order) : base(order) { }

    public override OrderStatusEnum Id {
        get { return OrderStatusEnum.Completed; }
    }
}

public enum OrderStatusEnum {
    New = 1,
    Pending = 2,
    Completed = 3
}

1 个答案:

答案 0 :(得分:0)

不确定是回答还是添加评论,但在类似的情况下,您的方法对我来说非常有效。

我还尝试使用Tarantino框架描述here的方法,但我发现从代码中扩展它更容易。