gpt4 book ai didi

c# - 关于工厂设计架构的问题

转载 作者:行者123 更新时间:2023-11-30 19:07:44 29 4
gpt4 key购买 nike

考虑这个例子

界面

interface IBusinessRules
{
string Perform();
}

继承者

class Client1BusinessRules: IBusinessRules
{
public string Perform()
{
return "Business rule for Client 1 Performed";
}
}

class Client2BusinessRules: IBusinessRules
{
public string Perform()
{
return "Business rule for Client 2 Performed";
}
}

class Client3BusinessRules: IBusinessRules
{
public string Perform()
{
return "Business rule for Client 3 Performed";
}
}

工厂类

class BusinessRulesFactory
{
public IBusinessRules GetObject(int clientIdentityCode)
{
IBusinessRules objbase = null;
switch (clientIdentityCode)
{
case 1:
objbase = new Client1BusinessRules();
break;
case 2:
objbase = new Client2BusinessRules();
break;
case 3:
objbase = new Client3BusinessRules();
break;
default:
throw new Exception("Unknown Object");
}
return objbase;
}
}

示例用法:

class Program
{
static void Main(string[] args)
{
BusinessRulesFactory objfactory = new BusinessRulesFactory ();
IBusinessRulesFactory objBase = objfactory.GetObject(2);
Console.WriteLine(objBase.Perform());

objBase = objfactory.GetObject(3);
Console.WriteLine(objBase.Perform());
Console.Read();
}
}

我的问题是,我如何在 ALgorithm1 类上添加另一个方法但不在界面中,因为我只是在特殊情况下使用它?

class Client1BusinessRules: IBusinessRules
{
public string Perform()
{
return "Client1 Business rules is Performed";
}


public string Calculate()
{
return "Additional functionality for CLient1";
}
}

我应该如何在 UI 上这样调用它

 objBase = objfactory.GetObject(1);
Console.WriteLine(objBase.Calculate());

还有其他解决办法吗?提前致谢

EDIT: I rewrite it to resemble my current project design

最佳答案

我假设您使用工厂类是为了:

  • 有一个标准外观接受导致业务规则选择配置的参数
  • 封装业务规则配置
  • 将用户与 IBusinessRules 的实际实现分离

因此我会通过引入新界面来解决你的问题

interface IComputableRules : IBusinessRules
{
string Calculate();
}

只要遵循基于接口(interface)的设计,将实际实例转换为不同于IBusinessRules 的接口(interface)就没有错。

IBusinessRules businessRule = objFactory.GetObject(...some input...)
...
// check if the computable service is supported and print the result
IComputableRules computable = businessRule as IComputableRules;
if (computable)
{
Console.WriteLine(computable.Calculate());
}

在这里,您可以将业务规则类视为服务提供者,它保证一些基本服务,以及根据业务规则的性质提供的可选附加服务。

注意:通过将 BusinessRulesFactory 转换为通用类,您可以将特定服务的指示作为工厂契约的一部分,并确保返回的业务规则实现将支持特定的(否则可选)服务。

class BusinessRulesFactory<TService> where TService : IBusinessRules
{
public TService GetObject(int clientIdentityCode)
{
// ... choose business rule in respect to both clientIdentityCode and TService
}
}

如果您不需要特定的附加服务可用,您只需使用 IBusinessRules 作为实际类型参数。

关于c# - 关于工厂设计架构的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3694145/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com