using System; using System.Text; using System.Threading; using System.Messaging; namespace QueueSpace { //外部依赖的接口,它屏蔽了mock对象和真对象 class Queue { public virtual object readMessage() { return null; } } //mock对象,模拟真对象的行为 class TestQueue : Queue { private int index = 0; private object[] Data = { "hello","world"}; public override object readMessage() { while (index < Data.Length) { object data = Data[index]; index++; return data; } Thread.Sleep(60*60*60); return null; } } //真正的业务对象 class WorkQueue : Queue { MessageQueue queue = null; public WorkQueue() { string queueName = ".\\Private$\\MSMQDemo"; if (MessageQueue.Exists(queueName)) { queue = new MessageQueue(queueName); } else { queue = MessageQueue.Create(queueName, false); queue.SetPermissions("Everyone", MessageQueueAccessRights.FullControl); } } public override object readMessage() { System.Messaging.Message message = queue.Receive(); string s =(string)message.Body; return (object)s; } } //对象工厂 class QueueFactory { public static Queue makeQueue() { return new TestQueue(); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using QueueSpace; namespace ConsoleApplication1 { class Program { static void Main(string[] args) { Queue queue = QueueFactory.makeQueue(); while (true) { object msg = queue.readMessage(); Console.WriteLine((string)msg); } } } }