我在实现工厂设计模式时遇到了麻烦。我查看了
http://dotnet.dzone.com/articles/design-patterns-c-factory,它非常接近我的设计,因为它是我不久前发现的第一个好例子。
我看了
Abstract Factory Design Pattern,但我的设计非常不同,我无法决定是否需要它。
现在,这就是它的样子。以前比较简单,和我的 CR5、interface、factory、CB_spec、El 等在同一个 Visual Studio 项目中。我必须按照设计讨论和 CR6 等分开的需要来移动东西。现在我遇到了一些编译问题,我不知道该怎么办。见下文。我的问题是关于下面的两个编译问题。
我的 iCR Visual Studio 项目:
public interface iCR
{
int CB_IO_Init(int slaveIndex);
int WritePortReady();
int WritePortBusy();
void initCRData(byte[] writeBuffer, byte[] statusBuffer, int SlaveIndex, USB_Comm.CB cb, int cr_Type);
int ProcessTWriting(ref Byte[] writeDat, ref Byte[] statusDat, ref Byte[] dataDumpWriteCheck);
void Failure(String message);
void Success(String message);
}
我的 CR_Factory Visual Studio 项目
namespace CR_Factory
{
public class Cr
{
}
public class CRFactory
{
public enum CRType
{
CR0,
CR1,
CR3,
CR4,
CR5,
CR6
}
public CRFactory()
{
}
public iCR GetCR(CRType type)
{
iCR cr = null;
switch (type)
{
case CRType.CR5:
cr = new CR5(); //**compile error..Cannot implicitly convert type ‘CR5’ to iCR’. An explicit conversion exists (are you missing a cast?)
break;
case CRType.CR6:
//not done yet
break;
default:
throw new ArgumentException(string.Format("A CR of type {0} cannot be found", Enum.GetName(typeof(CRType), type)));
}
return cr;
}
public CRType DetermineCR_Type(int type)
{
switch (type)
{
case 0:
return CRType.CR0;
//break;
case 1:
return CRType.CR1;
case 3:
return CRType.CR3;
case 4:
return CRType.CR4;
case 5:
return CRType.CR5;
case 6:
return CRType.CR6;
default:
throw new ArgumentException(string.Format("A type of type {0} cannot be found", type));
}
}
}
}
我的 CR5 Visual Studio 项目中有很多类,但现在我只是向您展示工厂中提到的部分。稍后我将创建一个 CR6 VS 项目等:
public class CR5 : iCR
{
CB_703 cb_specific = null;
//constructor
public CR5()
{
cb_specific = new CB_703(SlaveIndex);
}
public int CB_IO_Init(int SlaveIndex)
{
int result = -534;
result = cb_specific.IO_Init(SlaveIndex);
return result;
}
.
.
.
}
我有另一个 Visual Studio 项目(实际上是几个)实例化工厂并获取适当的类型。我们称它为 El:
namespace CrWr
{
public partial class PControl : UserControl
{
//setup
//constructor
public PControl()
{
}
/// <summary>
/// Get the P Control for chosen dll
/// </summary>
public Control GetPControl(USB_Comm.CB cbInstance, string dllSelected, THandlerApplication.Temp.TEMP[] temp, string dll, SC.SC.S_C c0)
{
cb = cbInstance;
createControls();
itsDll = dll;
tArr = temp;
cert = c0;
CR_Factory.CRFactory factory = new CR_Factory.CRFactory();
CRFactory.CRType type = factory.DetermineCR_Type(cr_Type);
try
{
cr = factory.GetCR(type); //**compile error GetCR is not supported by the language
}
catch (Exception ex)
{
Console.WriteLine(ex.InnerException);
}
return this;
}
private void OnP()
{
int result = -536;
while (rL)
{
result = cr.CB_IO_Init(SlaveIndex);
if (result == 0)
{
…
}
}
.
.
.
}