Java – the best way to avoid code duplication using fragments

I have an application ready to run in the Google play store, and now I'm executing the fragment

Therefore, I already have a Class A that extends some methods of B. now I have a class C that extends fragmentactivity, so now I need to use the same methods as those in class A. but here, because I'm extending fragmentactivity, I can't use class B, so here are the same duplicate methods as class A, but I need to reuse these methods

The following example shows my situation:

For example:

Current implementation

class A extends B{

one();
two();

}

After integrating the fragments,

For example:

class C extends FragmentActivity{

one();// same methods as in class A
two();// same methods as in class A

}

1) In this case, what is the best way to reuse the method?

2) In my mind, I have a method, like creating a class, making the method static, and reusing the methods in classes a and C, but my method is very good. I can make these methods static. Is this a good method?

3) I have considered another method of "strategy mode"

Eg:
class A extends ApiClass {
   private ClassContainingDupMethod strategy;
}

class N extends AnotherApiClass {
   private ClassContainingDupMethod strategy;

   public methodCallingDupMethod(){
      strategy.dupMethod();
   }
}

class ClassContainingDupMethod{
   public dupMethod(){;}
}

It is a "strategic pattern" A good idea, because I need to create ordinary class objects in these two classes

Any suggestions on this will be greatly appreciated

Solution

It's simpler than you describe All you need to do is create d like this:

public class D{
   one();
   two();
}

Change class A to use class D

public Class A{
       public D dLogic;
   }

Same as class C

public Class C extends FragmentActivity{
       public D dLogic;
   }

This is a very basic thing. In object-oriented programming, it is called composition

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>