I have three classes which have used one common interface. But in one class I have one more function (additional function())other than interface defined function. Suppose that this interface type reference is passed as a parameter to service layer method, if I have to call the additional function then what should I do?(i.e I have made interface driven desig开发者_如何学Pythonn while i have 90% similarity but in 10 % variation(like one additional function()). Is design ok? or we should try abstract class or else. Kindly suggest..........
Create another interface for the additional function - you can have a class implement multiple interfaces.
Make your service layer use this additional interface when required.
If you have the code:
void Op(IMyInterface x)
{
x.This();
x.That();
}
You could do:
void Op(IMyInterface x)
{
x.This();
x.That();
var y = x as SpecialClass;
if(y != null)
{
y.TheOther();
}
}
Although IMO that's a little messy - if you paste some code we can probably help you more.
To piggy-back off of Alex's answer, you could define a second interface called IMyOtherInterface with your extra method. Then do something like this:
void Op(IMyInterface x, IMyOtherInterface y) {
x.This();
x.That();
if(y != null) {
y.TheOther();
}
}
When you call the method, if your class implements both interfaces, you can pass it in twice. Otherwise just once. There's no reason your implementation has to know that it's the same class implementing both interfaces. If you're using VB or the 4.0 C#, you can mark that 2nd parameter 'optional'.
A third option is to just add your extra method to your original interface, but call it something more generic like "DoFinalization()" and let your implementation classes just have an empty implementation except for that one special case where you need it.
So really you have two interfaces, one of which implements the other.
public interface IMyInterfaceA
{
void Method1();
void Method2();
}
public interface IMyInterfaceB: IMyInterfaceA
{
void ExtraMethod();
}
Then your service layer methods should either accept IMyInterfaceA or IMyInterfaceB depending on whether they require ExtraMethod or not.
If you have a method that could accept IMyInterfaceA but would perhaps do something 'special' if IMyIntefaceB was available then you could use reflection (or just the 'as' operator), or perhaps better still just provide 2 overloaded versions of the method as the compiler should resolve the call to IMyInterfaceB where appropriate.
thanks for your responses. But, one of my lead looked at service layer level syntax like var y = x as SpecialClass; and said that it is not good design approach. He suggested me to use Factory at business manager level and then make this kind of casting.
精彩评论