简单工厂模式:通过专门定义一个类来负责创建其他类的实例,被创建的实例通常都具有共同的父类。
场景:公司的一个彩票红包推广活动项目,需要随机生成彩票号码,目前有双色球和大乐透,品种后期可能会新增。
彩票基础类:
1 public abstract class LotBase 2 { 3 ///4 /// 随机数生成器 5 /// 6 public static Random rand = new Random(); 7 //间隔符号 8 private string space = "-"; 9 10 ///11 /// 获取红球号码12 /// 13 ///14 protected abstract string GetRedche();15 /// 16 /// 获取篮球号码17 /// 18 ///19 protected abstract string GetBlueche();20 /// 21 /// 22 /// 23 ///24 protected string ToLotChe(List lotList)25 {26 StringBuilder lotChe = new StringBuilder();27 lotList.Sort();28 foreach (string item in lotList)29 {30 lotChe.Append(item);31 lotChe.Append(" ");32 }33 lotChe.Remove(lotChe.Length - 1, 1);34 return lotChe.ToString();35 }36 /// 37 /// 获取彩票号码38 /// 39 ///40 public string GetLotChe()41 {42 return string.Format("{0}{1}{2}", GetRedche(), space, GetBlueche());43 }44 }
双色球:
1 public class LotSSQ : LotBase 2 { 3 ///4 /// 双色球红球6个号码 5 /// 6 ///7 protected override string GetRedche() 8 { 9 int index = 0;10 List redList = new List { "01", "02", "03", "04", "05", "06", "07", "08", "09", "10", "11", "12", "13", "14", "15", "16", "17", "18", "19", "20", "21", "22", "23", "24", "25", "26", "27", "28", "29", "30", "31", "32", "33" };11 List redChe = new List ();12 for (int i = 0; i < 6; i++)13 {14 index = rand.Next(redList.Count - 1);15 redChe.Add(redList[index]);16 redList.RemoveAt(index);17 }18 return ToLotChe(redChe);19 }20 /// 21 /// 双色球篮球一个22 /// 23 ///24 protected override string GetBlueche()25 {26 string[] blueList = { "01", "02", "03", "04", "05", "06", "07", "08", "09", "10", "11", "12", "13", "14", "15", "16" };27 return blueList[rand.Next(15)];28 }29 }
大乐透:
1 public class LotDLT : LotBase 2 { 3 ///4 /// 大乐透红球5个号码 5 /// 6 ///7 protected override string GetRedche() 8 { 9 int index = 0;10 List redList = new List { "01", "02", "03", "04", "05", "06", "07", "08", "09", "10", "11", "12", "13", "14", "15", "16", "17", "18", "19", "20", "21", "22", "23", "24", "25", "26", "27", "28", "29", "30", "31", "32", "33", "34", "35" };11 List redChe = new List ();12 for (int i = 0; i < 5; i++)13 {14 index = rand.Next(redList.Count - 1);15 redChe.Add(redList[index]);16 redList.RemoveAt(index);17 }18 return ToLotChe(redChe);19 }20 /// 21 /// 大乐透篮球2个号码22 /// 23 ///24 protected override string GetBlueche()25 {26 int index = 0;27 List blueList = new List { "01", "02", "03", "04", "05", "06", "07", "08", "09", "10", "11", "12" };28 List blueChe = new List ();29 for (int i = 0; i < 2; i++)30 {31 index = rand.Next(blueList.Count - 1);32 blueChe.Add(blueList[index]);33 blueList.RemoveAt(index);34 }35 return ToLotChe(blueChe);36 }37 }
彩票工厂类:
1 public class LotFactory 2 { 3 public static LotBase GetLot(string lotcode) 4 { 5 LotBase lotCheBase = null; 6 switch (lotcode) 7 { 8 //双色球 9 case "SSQ":10 lotCheBase = new LotSSQ();11 break;12 //大乐透13 case "DLT":14 lotCheBase = new LotDLT();15 break;16 }17 return lotCheBase;18 }19 }