7. 仍然是一塊蛋糕
public class XmlLogger
{
public void Write(Dictionary<string, string> messages)
{
XElement element = new XElement(
new XElement("Record",
new XElement("Action", messages["Action"]),
new XElement("Detail", messages["Detail"]),
new XElement("LogTime", messages["LogTime"])
)
);
File.AppendAllText(string.Format("{0}_{1}.xml", DateTime.Now.ToString("yyyyMMdd"), Guid.NewGuid()),
element.ToString());
}
}
public class UserAppService
{
public void AddUser(UserInfo user)
{
…
XmlLogger log = new XmlLogger();
…
}
}
8. WHAT IF AGAIN…
某甲:長官說要改成寫進資料庫唷, ^.<
某乙:…(OS: what the…(╯-_-)╯╧╧ )
14. PLUGIN PATTERN實作(2)
建立TextLogger類別(plugin object),並實作
ILogger介面
public class TextLogger : ILogger
{
public void Write(Dictionary<string, string> messages)
{
StringBuilder sb = new StringBuilder();
messages.ToList().ForEach(c => sb.AppendLine(string.Format("{0}:{1}", c.Key, c.Value)));
sb.AppendLine();
File.AppendAllText(string.Format("{0}.txt", DateTime.Now.ToString("yyyyMMdd")),
sb.ToString());
}
}
15. PLUGIN PATTERN實作(3)
建立XmlLogger類別(plugin object) ,並實作
ILogger介面
public class XmlLogger : ILogger
{
public void Write(Dictionary<string, string> messages)
{
XElement element = new XElement(
new XElement("Record",
new XElement("Action", messages["Action"]),
new XElement("Detail", messages["Detail"]),
new XElement("LogTime", messages["LogTime"])
)
);
File.AppendAllText(string.Format("{0}_{1}.xml", DateTime.Now.ToString("yyyyMMdd"),
Guid.NewGuid()), element.ToString());
}
}
16. PLUGIN PATTERN實作(4)
建立一實作Factory Method Pattern的類別
public class LoggerFactory
{
private static ILogger _logger;
public static ILogger CreateLogger()
{
if (_logger == null)
{
string assemblyName = ConfigurationManager.AppSettings["AssemblyName"];
string classType = ConfigurationManager.AppSettings["ClassType"];
Assembly assembly = Assembly.Load(assemblyName);
_logger = assembly.CreateInstance(classType) as ILogger;
}
return _logger;
}
}
30. 參考
Patterns of Enterprise Application Architecture
Microsoft .NET: Architecting Applications for the Enterprise
Design Patterns: Elements of Reusable Object-Oriented Software
Provider Pattern
撰寫自己的 Configuration 區段 Part 1:不要再賴在 appSettings 的屋簷
下了,寫個自己的 Configuration 區段吧~
Provider Model Design Pattern and Specification, Part 1
ProviderBase Class
Designing loosely coupled components in .NET - Provider Pattern