java - 哪个模式在java : passing objects to a method or using composition?中耦合度较低

标签 java parameters composition coupling

//Ex1: (passing by object)
class A {
}

class B {
   void foo(A a) {
      <do something with a>
   }
}

//Ex2: (composition)
class C {
   A a
   void foo(){
      <do something with a>
   }
}

我的问题是:哪种模式的耦合度较低?哪种模式在现实世界中更受欢迎?

最佳答案

我将尝试解释松散耦合。

  1. 接口(interface)中的程序,这使得使用在运行时传递实现相同接口(interface)的不同类型的对象成为可能,这里来自不同继承树的类可以实现相同的接口(interface)。

例如:

 Animal is the Interface

    Dog class implements Animal
    Cat class implements Animal
    Lion class implements Animal

   /////////////////
   calling method
  /////////////////

   callAnimal(new Dog);



  /////////////////
   called method
  /////////////////

  public void (Animal a){

   // some code

  }

将不断变化的行为......封装到抽象类或接口(interface)中,因此当变化来临时很容易,并且由于它是松散耦合的,因此代码中断的可能性较小。

关于java - 哪个模式在java : passing objects to a method or using composition?中耦合度较低,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10682573/

相关文章:

asp.net-mvc - ASP.NET MVC 中的 UI 组合

java - 匿名线程类无法访问非静态实例变量

java - 在非静态方法中调用的静态方法的早期绑定(bind)

ASP.NET Core 自定义参数绑定(bind)

javascript - 如何获取 express.js 中的所有参数(post/get/etc.)

powershell - 使用参数但在 powershell 中保存 $args

C# - 对象组合 - 删除样板代码

plugins - MEF 和版本控制

java - 如何在单独的行上输出字符串数组,每行允许有 N 个字符

java - 在 Libgdx 中使用 SQLite 数据库