English 中文(简体)
如何在多个班级(活动)上添加同样的方法
原标题:How to add same method to multiple classes (activity)
  • 时间:2011-06-07 20:18:38
  •  标签:
  • java
  • android

我有3个A、B和C级。 后者将另一个D类。

D类所有A类、B类和C类均采用一种方法。

现在的问题是,A类、B类和C类应扩大不同类别,只使用D类相同的方法。

我认为,我应该复制并沿用我所有班子的方法。 在C中是否有这样的功能?

顺便说一句。 D类扩展活动,并采用一种方法管理A、B和C类的普通菜单(这是文体文件中报告的官方做法)。 然而,我需要开展这些活动,推广不同类型的活动,例如活动语言,而不仅仅是活动类别。

最佳回答

如果你的方法不需要进入私人国家,则在D类中增加固定方法,并从A、B、C类中采用静态方法。

如果你的方法确实需要进入私人国家,那么,如果你能够考虑是否有必要利用私人国家,为每个阶层增加一个一揽子-私人通道,然后使用A的方法。

否则,试图将某些逻辑推向一个共同的interface,而不是上下层。

否则,会试图将帮助者归入一类。 (例如,正如马克洛所示,组成而不是继承)

否则,重复A类、B类、C类的每一类方法。


作为共同接口办法的一个实例,加上D的一种静态方法:

interface MyThing
{
   public void doMyThing(String subject);
   public List<String> getThingNames();
}

class D
{
   static void doSomethingComplicatedWithMyThing(MyThing thing)
   {
      for (String name : thing.getThingNames())
      {
         boolean useThing = /* complicated logic */
         if (useThing)
           thing.doMyThing(name);
      }
   }
}

class A extends SomeClass implements MyThing
{
   /* implement methods of MyThing */

   void doSomethingComplicated()
   {
      D.doSomethingComplicatedWithMyThing(this);
   }
}

class B extends SomeOtherClass implements MyThing
{
   /* implement methods of MyThing */

   void doSomethingComplicated()
   {
      D.doSomethingComplicatedWithMyThing(this);
   }
}

class C extends YetAnotherClass implements MyThing
{
   /* implement methods of MyThing */

   void doSomethingComplicated()
   {
      D.doSomethingComplicatedWithMyThing(this);
   }
}
问题回答

You should have an instance variable of type D in each of your A, B, and C class definitions and use the method from that instance. That way A, B and C can still extend other classes.

在此案中,你赞成composition over inheritance





相关问题
Spring Properties File

Hi have this j2ee web application developed using spring framework. I have a problem with rendering mnessages in nihongo characters from the properties file. I tried converting the file to ascii using ...

Logging a global ID in multiple components

I have a system which contains multiple applications connected together using JMS and Spring Integration. Messages get sent along a chain of applications. [App A] -> [App B] -> [App C] We set a ...

Java Library Size

If I m given two Java Libraries in Jar format, 1 having no bells and whistles, and the other having lots of them that will mostly go unused.... my question is: How will the larger, mostly unused ...

How to get the Array Class for a given Class in Java?

I have a Class variable that holds a certain type and I need to get a variable that holds the corresponding array class. The best I could come up with is this: Class arrayOfFooClass = java.lang....

SQLite , Derby vs file system

I m working on a Java desktop application that reads and writes from/to different files. I think a better solution would be to replace the file system by a SQLite database. How hard is it to migrate ...

热门标签