/// <summary> /// Tries the enter traded. /// </summary> /// <returns>true</returns> /// <c>false</c> /// <param name="goods">Goods.</param> public bool TryEnterTraded(GoodsData goods) { if (goods == null) { throw new ArgumentNullException("goods"); } _goods = goods; return Monitor.TryEnter(_goods, _timeOut); }
/// <summary> /// 商品排序规则 /// </summary> /// <param name="x"></param> /// <param name="y"></param> /// <returns></returns> public virtual int SortGoods(GoodsData x, GoodsData y) { int result = 0; if (x == null && y == null) { return 0; } if (x != null && y == null) { return 1; } if (x == null) { return -1; } result = x.SeqNo.CompareTo(y.SeqNo); if (result == 0) { x.Id.CompareTo(y.Id); } return result; }
protected override object ProduceGoods(GoodsData goods, int goodsNum) { //创建物品对象 }
protected override bool HasTraded(BaseUser user, GoodsData goods, int goodsNum, out double amount, out TradeErrorCode errorCode) { //检查是否可交易 }
/// <summary> /// Trades the goods. /// </summary> /// <returns><c>true</c>, if goods was traded, <c>false</c> otherwise.</returns> /// <param name="user">User.</param> /// <param name="goods">Goods.</param> /// <param name="goodsNum">Goods number.</param> /// <param name="errorCode">Error code.</param> public bool TradeGoods(IUser user, GoodsData goods, int goodsNum, out TradeErrorCode errorCode) { bool result = false; if (_tradeStrategy.TryEnterTraded(goods)) { try { double payAmount; if (HasTraded(user, goods, goodsNum, out payAmount, out errorCode)) { var items = ProduceGoods(goods, goodsNum); if (SendGoods(user, items) && PayAmount(user, goods.TradeType, payAmount)) { TradeSuccess(user, goods, goodsNum, payAmount, items); errorCode = TradeErrorCode.Sucess; result = true; } else { errorCode = TradeErrorCode.Fail; } } } finally { _tradeStrategy.ExitTraded(); } } else { errorCode = TradeErrorCode.TradeTimeout; } return result; }
/// <summary> /// 检查是否可交易 /// </summary> /// <param name="user"></param> /// <param name="goods"></param> /// <param name="goodsNum"></param> /// <param name="amount"></param> /// <param name="errorCode"></param> /// <returns></returns> protected abstract bool HasTraded(IUser user, GoodsData goods, int goodsNum, out double amount, out TradeErrorCode errorCode);
/// <summary> /// 生产物品 /// </summary> /// <param name="goods"></param> /// <param name="goodsNum"></param> /// <returns></returns> protected abstract object ProduceGoods(GoodsData goods, int goodsNum);
/// <summary> /// 交易成功 /// </summary> /// <param name="user"></param> /// <param name="goods"></param> /// <param name="goodsNum"></param> /// <param name="payAmount"></param> /// <param name="items"></param> protected virtual void TradeSuccess(IUser user, GoodsData goods, int goodsNum, double payAmount, object items) { }