无废话C#设计模式之八:Facade


  本系列文章将向大家介绍一下C#的设计模式,此为第八篇文章,相信对大家会有所帮助的。废话不多说,继续来看。

  意图

  为子系统中的一组接口提供一个一致的界面,Facade模式定义了一个高层接口,这个接口使得这一子系统更加容易使用。

  场景

  在一个为游戏充值的网站中,创建订单需要与三个外部接口打交道:

  用户系统:根据用户名获取用户ID、查看用户是否已经激活了游戏

  卡系统:查看某种类型的充值卡是否还有库存

  充值系统:创建一个订单,并且返回订单号

  如果直接让网站和三个外部接口发生耦合,那么网站因为外部系统接口修改而修改的概率就很大了,并且就这些小接口来说并不是十分友善,它们提供的大多数是工具方法,具体怎么去使用还是要看充值网站创建订单的逻辑。

  Facade的思想就是在小接口上封装一个高层接口,屏蔽子接口的调用,提供外部更简洁,更易用的接口。

  示例代码

以下为引用的内容:

  using System;
  using System.Collections.Generic;
  using System.Text;
  namespace FacadeExample
  {
  class Program
  {
  static void Main(string[] args)
  {
  PayFacacde pf = new PayFacacde();
  Console.WriteLine("order:" + pf.CreateOrder("yzhu", 0, 1, 12) + " created");
  }
  }
  class PayFacacde
  {
  private AccountSystem account = new AccountSystem();
  private CardSystem card = new CardSystem();
  private PaySystem pay = new PaySystem();
  public string CreateOrder(string userName, int cardID, int cardCount, int areaID)
  {
  int userID = account.GetUserIDByUserName(userName);
  if (userID == 0)
  return string.Empty;
  if (!account.UserIsActived(userID, areaID))
  return string.Empty;
  if (!card.CardHasStock(cardID, cardCount))
  return string.Empty;
  return pay.CreateOrder(userID, cardID, cardCount);
  }
  }
  class AccountSystem
  {
  public bool UserIsActived(int userID, int areaID)
  {
  return true;
  }
  public int GetUserIDByUserName(string userName)
  {
  return 123;
  }
  }
  class CardSystem
  {
  public bool CardHasStock(int cardID, int cardCount)
  {
  return true;
  }
  }
  class PaySystem
  {
  public string CreateOrder(int userID, int cardID, int cardCount)
  {
  return "0000000001";
  }
  }
  }


« 
» 
快速导航

Copyright © 2016 phpStudy | 豫ICP备2021030365号-3