从Prism中学习设计模式之Facade模式

Prism的Loging是一个相对独立的功能模块,基于最基本的Log功能,可以有Trace、Console等方式进行日志的输出。

当然除了以上所提的Log功能,还可以本地化存储、网络存储日志等复杂的功能。将这些复杂功能封装,暴露一部分功能或者简单的方式供外部使用,Prism使用Facade模式来实现日志功能。

关于Facade模式的讲解,Link:http://www.cnblogs.com/cjfwu/archive/2013/03/23/2977541.html

上文详细描述了Facade模式的定义、实现、架构图。

Prism中默认实现了Trace,Console

 1     public class TextLogger : ILoggerFacade, IDisposable
 2     {
 3         private readonly TextWriter writer;
 4 
 5         public TextLogger()
 6             : this(Console.Out)
 7         {
 8         }
 9 
10         public TextLogger(TextWriter writer)
11         {
12             if (writer == null)
13                 throw new ArgumentNullException("writer");
14 
15             this.writer = writer;
16         }
17 
18         public void Log(string message, Category category, Priority priority)
19         {
20             string messageToLog = String.Format(CultureInfo.InvariantCulture, Resources.DefaultTextLoggerPattern, DateTime.Now,
21                                                 category.ToString().ToUpper(CultureInfo.InvariantCulture), message, priority.ToString());
22 
23             writer.WriteLine(messageToLog);
24         }
25 
26         protected virtual void Dispose(bool disposing)
27         {
28             if (disposing)
29             {
30                 if (writer != null)
31                 {
32                     writer.Dispose();
33                 }
34             }
35         }
36 
37         public void Dispose()
38         {
39             Dispose(true);
40             GC.SuppressFinalize(this);
41         }
42     }
43 
44     public class TraceLogger : ILoggerFacade
45     {
46         public void Log(string message, Category category, Priority priority)
47         {
48             if (category == Category.Exception)
49             {
50                 Trace.TraceError(message);
51             }
52             else
53             {
54                 Trace.TraceInformation(message);
55             }
56         }
57     }

从上代码可以看到通过ILoggerFacade接口实现Logger功能。实现例子:

 1     internal class MockLogger : ILoggerFacade
 2     {
 3         public string LastMessage;
 4 
 5         public void Log(string message, Category category, Priority priority)
 6         {
 7             LastMessage = message;
 8         }
 9     }
10 
11         [TestMethod]
12         public void SubmitLogsAnEntry()
13         {
14             var logger = new MockLogger();
15             var ordersService = new XmlOrdersService(logger);
16             var document = new XDocument();
17 
18             var order = new Order
19             {
20                 TickerSymbol = "TEST"
21             };
22 
23             ordersService.Submit(order, document);
24 
25             StringAssert.Contains(logger.LastMessage, "TEST");
26 
27         }

 

 

 

posted @ 2013-04-20 22:23  老鱼_678  阅读(728)  评论(0编辑  收藏  举报