抽象类与接口的开发考虑

        对于Java的抽象类与接口的分别的论述网上有很多,但到真正在开发中什么时候使用却很少人去问到

以下一段文字摘自Abstract Methods and Classes

  • Consider using abstract classes if any of these statements apply to your situation:()
    • You want to share code among several closely related classes.(当几个相近似的类共享代码的时候)
    • You expect that classes that extend your abstract class have many common methods or fields, or require access modifiers other than public (such as protected and private).(你期望继承你的抽象类的类集有非常多共同的方法和属性或者需要访问修饰符是非公共的)
    • You want to declare non-static or non-final fields. This enables you to define methods that can access and modify the state of the object to which they belong.(你想声明非静态和非final字段。这些字段允许你去定义一些能够访问和修改对象的属性状态的方法。)
  • Consider using interfaces if any of these statements apply to your situation:
    • You expect that unrelated classes would implement your interface. For example, the interfaces Comparable and Cloneable are implemented by many unrelated classes.(你期望 非关联的类也要实现你的接口,例如,这接口 Comparable and Cloneable 被很多没有联系的类的实现了 )
    • You want to specify the behavior of a particular data type, but not concerned about who implements its behavior.(你想规范一些特定的数据类的行为,但从不关心谁实现了行为)
    • You want to take advantage of multiple inheritance of type.(你想实现多重继承)

     

          总的来说接口比抽象类更灵活,因为它只是代表了一种标准行为,它并不会对你的一个类的所有行为进行归属。

           这么说吧,抽象类跟其它父类一样。都是一个爸爸,只是这个爸爸是抽象,他只是负责把你生了,但他已经去世了,或者不会动了。他无办法实例化。而你只能继承他的基因,他却无法教你做人(没有具体行为内容),父亲只能有一个。而接口是一个职称,每当你有一个职称,你必须有一些行为。但你可以有多个职称。职称只是规范了你这个人的行为,父亲则是决定你的基因,决定了你的从属。当你跟另外一个人有同一个父亲时,你们是有血缘关系的。当你们都有相同的职称时,你们可能一点关系都没,只那么巧干相同的一类事。这在面向对象开发实际应用中常常遇到的,你是要一个爸爸,还是要一个职能。爸爸的好处是决定了你只能跟一个爸爸,而且决定这个类的从属基因,并且能决定一些非静态和非final的属性。而接口的好处是只是给你一个规范却不对的血缘进行更改。这个类的作用,这个类的意义和类别跟接口一点关都没有,只是说这个类要这么干。

          从软件工程的角度,工程师是更喜欢用接口,因为上级的工程师定义了接口,规范了行为,而下级工程师只需要实现,而且无论用什么类来实现,这样既维持了工程的标准性,又大大增加了灵活和扩展性。使用注入技术更可以增加灵活的更改接口实现。而无需要更改实例化代码。

          

猜你喜欢

转载自only-life.iteye.com/blog/2227607