模式应用 - 利用工厂模式制作自己的"小程序测试工厂"

在平时开发程序的过程中,自己经常会写一些控制台小程序进行测试某个功能,事后我们会寻找这些小程序,

如果不仔细管理,经常会找不到。

由于每个控制台小程序都有自己独立的 Main方法,所以我们不能把他们都放在一个Solution里面,这样

在编译整个项目的时候会通不过,但是又不想为每个小程序都单独建立一个项目,这样又太浪费,因为

每个都是一个非常简单的代码文件。

于是我想到了利用工厂模式,我是这样做的:

首先创建一个ITestCase接口,它有一个Run方法。

namespace SharpTrainer

{

interface ITestCase

{

void Run();

}

}

接着我们为我们的每个小程序建立自己的TestCase类,例如:

你可以这样做:

class TestCase1: ITestCase

{

public void Run()

{

....;

}

}

class TestCase2: ITestCase

{

public void Run()

{

....;

}

}

我举个我实际的TestCase如下:

using System;

namespace SharpTrainer

{

class TestRefParam:ITestCase

{

public void Run()

{

string first = "first";

string second = "second";

Utility.Swap(ref first, ref second);

System.Console.WriteLine(

@"first = {0}, second = {1}",

first, second);

System.Console.ReadLine();

}

}

}

Utility类的代码如下:

namespace SharpTrainer

{

public class Utility

{

public static void Swap(ref string first, ref string second)

{

string temp = first;

first = second;

second = temp;

}

}

}

接下来我们便要创建App配置文件,用于等下

根据 config 文件的设置用反射创建相应的 TestCase 类型实例返回.

App.Config代码如下:

<?xml version="1.0" encoding="utf-8" ?>

<configuration>

<appSettings>

<add key="testAssembly" value="SharpTrainer"></add>

<add key="testCaseName" value="TestRefParam"></add>

</appSettings>

</configuration>

最后在Main方法中利用反射来运行我们的TestCase,如下:

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

using System.Reflection;

using System.Configuration;

namespace SharpTrainer

{

class Program

{

static void Main(string[] args)

{

string AssemblyName = ConfigurationSettings.AppSettings["testAssembly"];

string CaseName = ConfigurationSettings.AppSettings["testCaseName"];

string className = AssemblyName + "." + CaseName;

ITestCase testCase = (ITestCase)Assembly.Load(AssemblyName).CreateInstance(className);

testCase.Run();

}

}

}

运行结果如下:

first = second, second = first

这样,以后我就可以不断地增加小程序测试用例类,每个TestCase类实现 ITestCase接口,而逻辑都写在

Run方法里。

我们要运行哪个 TestCase 只要将App.Config里testCaseName的键值改成相应的TestCase类名就好了。

以上就是我利用工厂模式实现的自己测试小程序的用例测试工厂。