Reputation: 91
I have two implementations with the same name for my interface as follows:
interface IDBCaller
{
IEnumerable<User> RetrieveUserList();
void Method1();
void Method2();
}
//First implementation of IDBCaller in project1
class DBCaller : IDBCaller
{
public IEnumerable<User> RetrieveUserList()
{
return new List<User>();
}
public void Method1()
{
//doing something
}
public void Method2()
{
//doing something
}
}
//Second implementation of IDBCaller in project2
class DBCaller: IDBCaller
{
public IEnumerable<User> RetrieveUserList()
{
return null; //Currently returns null but the desire state is to call the RetrieveUserList in Implementation1 from project 1
}
public void Method1()
{
//doing something
}
public void Method2()
{
//doing something
}
}
Implementation 1 and 2 have the same RetrieveUserList()
method.
When the RetrieveUserList()
is called from Implementation 2, I want the call to be redirected to the same method in Implementation 1.
Upvotes: 0
Views: 699
Reputation: 241
In addition to what Jens said, you could use the decorator pattern.
public interface IDBCaller
{
IEnumerable<User> RetrieveUserList();
}
public class Implementation1 : IDBCaller
{
public IEnumerable<User> RetrieveUserList()
{
return new List<User>();
}
}
public class Implementation2 : IDBCaller
{
IDBCaller decoratedImplementation;
public Implementation2(IDBCaller decoratedImplementation)
{
this.decoratedImplementation = decoratedImplementation;
}
public IEnumerable<User> RetrieveUserList()
{
return this.decoratedImplementation.RetrieveUserList();
}
}
Upvotes: 2
Reputation: 5070
You could use inheritance e.g:
interface IDBCaller
{
IEnumerable<User> RetrieveUserList();
}
class Implementation1 : IDBCaller
{
public virtual IEnumerable<User> RetrieveUserList()
{
return new List<User>();
}
}
class Implementation2 : Implementation1
{
public override IEnumerable<User> RetrieveUserList()
{
return base.RetrieveUserList();
}
}
Or use a base class with the RetrieveUserList implementation
interface IDBCaller
{
IEnumerable<User> RetrieveUserList();
void Method1();
void Method2();
}
class ImplementationBase
{
public virtual IEnumerable<User> RetrieveUserList()
{
return new List<User>();
}
}
class Implementation1 : ImplementationBase, IDBCaller
{
public void Method1()
{
throw new NotImplementedException();
}
public void Method2()
{
throw new NotImplementedException();
}
}
class Implementation2 : ImplementationBase, IDBCaller
{
public void Method1()
{
throw new NotImplementedException();
}
public void Method2()
{
throw new NotImplementedException();
}
}
Upvotes: 5