Factory:工厂角色
Product:抽象产品角色
ConcreteProduct:具体产品角色
下面是一个支付方式的例子:(vs c#控制台)
AbstractPay:抽象支付类
namespace SimpleFactoryModel { abstract class AbstractPay { public abstract string pay(); //支付方式 } }
CashPay:现金支付类:
namespace SimpleFactoryModel { class CashPay:AbstractPay { public override string pay() { //现金支付 return "现金支付"; } } }
CardPay:刷卡支付类
namespace SimpleFactoryModel { class CardPay:AbstractPay { public override string pay() { //刷卡支付 return "刷卡支付"; } } }
MovePay:移动支付类
namespace SimpleFactoryModel { class MovePay:AbstractPay { public override string pay() { //移动支付 return "移动支付"; } } }
PayFactory:支付工厂
using System; using System.Reflection; namespace SimpleFactoryModel { class PayFactory { string className= XMUntil.GetClassName(); AbstractPay ap = null; public void pay() { switch (className) { case "MovePay": ap = new MovePay(); break; case "CardPay": ap = new CardPay(); break; case "CashPay": ap = new CashPay(); break; default: ; break; } Console.WriteLine(ap.pay()); Console.ReadKey(); /* //通过反射将类名字符串转为同名类(进阶) Type t; t = Type.GetType("SimpleFactoryModel."+XMUntil.GetClassName()); object obj = Activator.CreateInstance(t); AbstractPay ap = (AbstractPay)obj; Console.WriteLine(ap.pay()); Console.ReadKey(); */ } } }
config.xml:配置文件
<?xml version="1.0" encoding="utf-8" ?> <config> <className>MovePay</className> </config>
XMUntil:xml解析
using System; using System.Xml; namespace SimpleFactoryModel { static class XMUntil { /// <summary> /// xml文件解析 /// </summary> /// <returns></returns> public static string GetClassName() { try { string path = AppDomain.CurrentDomain.BaseDirectory + "Config.xml"; XmlDocument doc = new XmlDocument(); doc.Load(path); XmlNode config = doc.SelectSingleNode("config"); XmlNodeList className = config.ChildNodes; return className[0].InnerText; } catch (Exception) { throw; } } } }
Client:客户端
using System; using System.Reflection; namespace SimpleFactoryModel { class Client { static void Main(string[] args) {
PayFactory factory = new PayFactory();
factory.pay();
}
}
}