技术宅,fat-man

增加语言的了解程度可以避免写出愚蠢的代码

导航

测试:mock对象

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);
            }
        }
    }
}

 

posted on 2012-09-22 17:16  codestyle  阅读(354)  评论(0编辑  收藏  举报