Reputation: 121
In my code base there is an existing ConnectionFactory which is used in multiple places. I have recently added AdvancedConnection which is an extension of Connection class. In the AdvancedConnectionFactory, in CreateAdvancedConnection I would like to use the template logic which is same as in ConnectionFactory. And then return the new instance of AdvancedConnection with options. My AddTemplate logic is big and I don't want to duplicate it. What would be the recommended way of using the AddTemplate logic in AdvancedConnectionFactory?
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);
}
}
Upvotes: 1
Views: 90
Reputation: 834
I think you can find a lot of ways to do it, but personally I would choose this approach:
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 logic needs to be protected)
This is an example how it would work: https://dotnetfiddle.net/SkQC4E
Upvotes: 1