从这里:“我有不同的类,这些类将为我处理检索和存储数据。”
如果我没看错的话,听起来您已经有了对属性进行操作的类。您可以创建一个所有这些类都基于的接口,然后使用类工厂通过将属性名称传递给工厂来返回对给定“属性”进行操作的类。
首先,在网络上搜索“C# 类工厂”,将会有大量关于类工厂模式如何工作的信息。
本质上,类工厂有一个接口、一个或多个实现该接口的类,以及一个返回实现该接口的类的实例的工厂。然后应用程序可以使用所有这些部分来执行某些任务。
这是我拼凑起来的一个小例子。
IMathOperation.cs
// The interface that all factory classes must implement:
interface IMathOperation
{
string getName();
string performOperation(int a, int b);
}
实现接口的类:
添加.cs
public class Add : IMathOperation
{
public string getName()
{
return "Addition";
}
public string performOperation(int a, int b)
{
return string.Format("{0} + {1} = {2}", a, b, a+b);
}
}
减去.cs
public class Subtract : IMathOperation
{
public string getName()
{
return "Subtraction";
}
public string performOperation(int a, int b)
{
return string.Format("{0} - {1} = {2}", a, b, a-b);
}
}
乘法.cs
public class Multiply : IMathOperation
{
public string getName()
{
return "Multiplication";
}
public string performOperation(int a, int b)
{
return string.Format("{0} * {1} = {2}", a, b, a*b);
}
}
Divide.cs
public class Divide : IMathOperation
{
public string getName()
{
return "Division";
}
public string performOperation(int a, int b)
{
return string.Format("{0} / {1} = {2}", a, b, b != 0? ((float)((float)a / (float)b)).ToString() : "Divide by zero error");
}
}
MathFactory.cs
class MathFactory
{
public static IMathOperation getFactory(string mathOp)
{
switch (mathOp.ToUpper())
{
case "ADD":
return new Add();
case "SUB":
return new Subtract();
case "MUL":
return new Multiply();
case "DIV":
return new Divide();
}
return null;
}
}
程序.cs
using System;
namespace ClassFactory_C_Sharp {
class Program
{
static void Main(string[] args)
{
IMathOperation op;
Console.WriteLine("Hello Math Factory!\n");
// try all the class factories
op = MathFactory.getFactory("Add");
Console.WriteLine(string.Format("{0}: {1}", op.getName(), op.performOperation(2,3)));
op = MathFactory.getFactory("Sub");
Console.WriteLine(string.Format("{0}: {1}", op.getName(), op.performOperation(2,3)));
op = MathFactory.getFactory("Mul");
Console.WriteLine(string.Format("{0}: {1}", op.getName(), op.performOperation(2,3)));
op = MathFactory.getFactory("Div");
Console.WriteLine(string.Format("{0}: {1}", op.getName(), op.performOperation(2,3)));
// try one more divide that causes error
Console.WriteLine(string.Format("{0}: {1}", op.getName(), op.performOperation(2,0)));
}
} }
输出:
Hello Math Factory!
Addition: 2 + 3 = 5
Subtraction: 2 - 3 = -1
Multiplication: 2 * 3 = 6
Division: 2 / 3 = 0.6666667
Division: 2 / 0 = Divide by zero error