【问题标题】:Multiple factory functions specific to a type OR one generic factory function and then cast to type?特定于一种类型的多个工厂函数或一个通用工厂函数然后转换为类型?
【发布时间】:2018-12-21 14:12:24
【问题描述】:

我正在创建一个 WCF 服务来充当我们系统的 DAL。

每个 Db 都有一个继承自接口的类来描述它的功能,例如

public class <DbName>Service : Database, IProductService, IOrderService

如果外部系统调用 WCF 接口上的函数,例如

public int CreateProduct(IProduct product, string databaseId)

此功能需要与连接到请求的 Db 的 IProductService 进行交互,并非所有数据库都具有相同的功能,有些具有其他产品不能。

我是否应该有多个工厂函数可以使用 databaseId 上的开关返回每种类型,例如

public static IProductService GetProductServiceFromConfig(string databaseId)
{
    switch (systemId)
    {
        case DatabaseIds.<DbName>:
            system = new <DbName>Service(new <DbName>ConfigSettings());
            break;
        default:
            throw new ArgumentOutOfRangeException();

    }
}

或者:

一个返回 IDatabase 的函数,该函数的调用者可以将其转换为所需的类型,例如

public static IDatabase GetDatabaseServiceFromConfig(string systemId)
{
    // Switch Case and return IDatabase, as each database must inherit from IDatabase
}

函数调用:

var service = DatabaseServiceFactory.GetDatabaseServiceFromConfig(DatabaseIds.<DatabaseName>) as IProductService

if(service != null) { /* The service implements the type IProductService therefore has access to the function you need */ } 

【问题讨论】:

    标签: c# asp.net wcf


    【解决方案1】:

    为清楚起见,我创建了如下解决方案

    public static T GetDatabaseServiceFromConfig<T>(string databaseId)
    {
        object system = null;
    
        switch (databaseId)
        {
            case DatabaseIds.<DbName>:
                system = new <DbName>Service(new <DbName>ConfigSettings());
                break;
            // More cases
            default:
                // System not found
                throw new ArgumentOutOfRangeException(databaseId);
            }
    
        if (!(system is T))
        {
            throw new NotImplementedException("Database type was found and created but does not implement interface: " + typeof(T));
        }
    
        // Safe cast
        return (T)system;
    }
    

    实施:

    var service = DatabaseServiceFactory.GetDatabaseServiceFromConfig<IProductService>(DatabaseIds.<DbName>);
    
    // object now has access to functions on IProductService
    service.CreateProduct(/*Params*/);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-06-21
      • 2021-04-19
      • 1970-01-01
      • 2021-02-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多