【问题标题】:Is this considered as good approach of using interface type in class这是否被认为是在类中使用接口类型的好方法
【发布时间】:2021-12-18 12:46:03
【问题描述】:

假设我有如下代码

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 之外是否还有更好的方法?

【问题讨论】:

    标签: oop interface


    【解决方案1】:

    您好,欢迎来到 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);
    }
    

    【讨论】:

    • 嗯,是的,有道理,谢谢你的回复,我一定会记住的
    猜你喜欢
    • 2019-12-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-12-18
    • 1970-01-01
    • 2012-10-22
    • 2013-04-12
    相关资源
    最近更新 更多