說我有一個代碼如下
interface Interface1
{
void method1();
}
interface Interface2
{
void method2();
}
class ClassWithInterfaces : Interface1,Interface2
{
void method1(){}
void method2(){}
}
現在在我的“經理”類中,我按如下方式實作:
public OtherClass
{
Interface1 interface1;
Interface2 interface2;
public void someMethod()
{
ClassWithInterfaces classWithInterfaces = new ClassWithInterfaces();
interface1 = classWithInterfaces;
interface2 = classWithInterfaces
}
}
我不認為這是正確的方法,但是我無法提出其他解決方案,如果您問這個問題,我無法在我的專案中使用依賴注入框架。你能告訴我除了 DI 之外還有更好的方法嗎?
uj5u.com熱心網友回復:
你好,歡迎來到 Stack Overflow :-)
您不必使用框架來進行 DI。事實上,有些語言使得無法使用 DI 框架 - 例如,C 。無論如何,就您而言,進行 DI 的正確方法是這樣的:
interface Interface1
{
void method1();
}
interface Interface2
{
void method2();
}
interface Interface3 : Interface1, Interface2
{
void method1();
void method2();
}
class ClassWithInterfaces : Interface3
{
void method1(){}
void method2(){}
}
public OtherClass
{
Interface3 m_interface3;
OtherClass(Interface3 interface3)
{
m_interface3 = interface3;
}
public void someMethod()
{
m_interface3.method1();
m_interface3.method2();
}
}
// And now the usage:
public main()
{
ClassWithInterfaces classWithInterfaces = new ClassWithInterfaces();
OtherClass otherClass = new OtherClass(classWithInterfaces);
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/350743.html
