重构静态工厂 class,其中另一个工厂 class 需要使用其私有方法

Refactoring on static Factory class where the other Factory class needs to use its private method

在我的代码库中有一个现有的 ConnectionFactory,它在多个地方使用。我最近添加了 AdvancedConnection,它是 Connection class 的扩展。 在 AdvancedConnectionFactory 中,在 CreateAdvancedConnection 中,我想使用与 ConnectionFactory 中相同的模板逻辑.然后 return 带有选项的 AdvancedConnection 的新实例。我的 AddTemplate 逻辑很大,我不想重复它。在 AdvancedConnectionFactory 中使用 AddTemplate 逻辑的推荐方法是什么?

public static class ConnectionFactory
{
    public static Connection CreateConnection(Options options)
    {
        return new IntermediateMethod1(options);
    }

    private static Connection IntermediateMethod1(Options options)
    {
        AddTemplate(options);
        return new Connection(options);
    }

    private static void AddTemplate(Options options)
    {
        // do some templating stuff on the connection string
        options.ConnectionString = "some templated string";
    }
}

public static class AdvancedConnectionFactory
{
    public static AdvancedConnection CreateAdvancedConnection(Options options)
    {
        // Need to use the same logic of AddTemplate from ConnectionFactory
        return new AdvancedConnection(options);
    }
}

我想你可以找到很多方法,但我个人会选择这种方法:

public abstract class ConnectionFactoryBase<T> where T : class, new()
{
    private static T _instance;

    public static T GetInstance()
    {
        if(_instance == null)
            _instance = new T();
        return _instance;
    }
    
    public abstract Connection CreateConnection(Options options);

    protected void AddTemplate(Options options)
    {
        // do some templating stuff on the connection string
        options.ConnectionString = "some templated string";
    }
}

public class ConnectionFactory : ConnectionFactoryBase<ConnectionFactory>
{
    public override Connection CreateConnection(Options options)
    {
        return IntermediateMethod1(options);
    }

    private Connection IntermediateMethod1(Options options)
    {
        AddTemplate(options);
        return new Connection(options);
    }
}

public class AdvancedConnectionFactory : ConnectionFactoryBase<AdvancedConnectionFactory>
{
    public override Connection CreateConnection(Options options)
    {
        return CreateAdvancedConnection(options);
    }
    
    public AdvancedConnection CreateAdvancedConnection(Options options)
    {
        AddTemplate(options);
        return new AdvancedConnection(options);
    }
}

(AddTemplate逻辑需要保护)

这是一个工作原理示例: https://dotnetfiddle.net/SkQC4E