这被认为是在 class 中使用接口类型的好方法吗?
Is this considered as good approach of using interface type in class
假设我有一个代码如下
interface Interface1
{
void method1();
}
interface Interface2
{
void method2();
}
class ClassWithInterfaces : Interface1,Interface2
{
void method1(){}
void method2(){}
}
现在在我的“经理”中 class 我按如下方式实现:
public OtherClass
{
Interface1 interface1;
Interface2 interface2;
public void someMethod()
{
ClassWithInterfaces classWithInterfaces = new ClassWithInterfaces();
interface1 = classWithInterfaces;
interface2 = classWithInterfaces
}
}
我不认为这是正确的方法 howewer 我不能想出其他解决方案如果你问我不能在我的项目中使用依赖注入框架。你能告诉我除了 DI 之外还有更好的方法吗?
您好,欢迎来到 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);
}
假设我有一个代码如下
interface Interface1
{
void method1();
}
interface Interface2
{
void method2();
}
class ClassWithInterfaces : Interface1,Interface2
{
void method1(){}
void method2(){}
}
现在在我的“经理”中 class 我按如下方式实现:
public OtherClass
{
Interface1 interface1;
Interface2 interface2;
public void someMethod()
{
ClassWithInterfaces classWithInterfaces = new ClassWithInterfaces();
interface1 = classWithInterfaces;
interface2 = classWithInterfaces
}
}
我不认为这是正确的方法 howewer 我不能想出其他解决方案如果你问我不能在我的项目中使用依赖注入框架。你能告诉我除了 DI 之外还有更好的方法吗?
您好,欢迎来到 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);
}