公司有做一个手机统计的饼状图
后台读取数据时频繁的读取xml进行匹配(手机品牌和型号都是放到xml中),频繁的load xml无疑会增加整个页面的加载时间
项目经理教我使用单例模式,仅需要一次load xml,就可以在全局中使用,类似于Application或Session
首先,建一个公共的类DataService.cs
private static DataService instance; private DataService() { } public XmlDocument xmldoc_MobileBrand; public XmlDocument xmldoc_City; public XmlDocument xmldoc_Province; public static DataService GetInstance() { if (instance == null) { ///若实例不存在,则new一个新实例,否则返回已有的实例 if (instance == null) { instance = new DataService(); } } return instance; }
使用方法很简单,第一次使用
XmlDocument xd = new XmlDocument(); xd.Load(Server.MapPath("~/XmlConfig/MobileBrand.xml")); DataService.GetInstance().xmldoc_MobileBrand = xd;
这样,单例中的xmldoc_MobleBrand就被实例化,然后就可以在全局中访问了。
其他地方调用:
XmlDocument xd = new XmlDocument(); xd = DataService.GetInstance().xmldoc_MobileBrand;