簡體   English   中英

在 static 工廠 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中相同的模板邏輯。 然后返回帶有選項的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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM