Put the interface in the package to get started.

I need to start work from two different screens with two different models, but both models have common information that I need in a new action. The problem is that I cannot get these models to propagate from the same parent, because one of the models already extends one parent. I was thinking of creating an interface that contains common methods, but if I do, how can I put this interface in the package needed to run the next action?

I will add simplified code to clarify the situation:

public class A extends Model implements CustomInterface { String name; String address; public String getName(){ return name; } public String getAddress() { return address; } } public class B implements CustomInterface { String name; public String getName() { return name; } } public interface CustomInterface { String getName(); } 

My problem is that I need to get started with a package with general information between both models. So, I would like to add CustomInterface to the package. How can i do this?

Thanks in advance.

+5
source share
2 answers

So, I would like to put CustomInterface in the package

you can let CustomInterface extend Parcelable . For instance.

  public interface CustomInterface extends Parcelable { String getName(); } 

thus, classes implementing CustomInterface will need to implement the method defined in the Parcelable interface. If they are executed correctly, you can easily pass these objects

+11
source

Create a singleton class, then you can exchange data without passing:

 public class MySingleton { private static MySingleton instance; public String customVar; public static MySingleton getInstance() { if (instance == null) { // Create the instance instance = new MySingleton(); } // Return the instance return instance; } private MySingleton() { // Constructor hidden because this is a singleton } public void getSomeData() { return something; } public void getSomeOtherData() { return somethingelse; } } 

Then in your classes:

 public class A extends Model { String name; String address; public String getName(){ return name; } public String getAddress() { return address; } public String doSomethingWithSharedData(){ MySingleton model = MySingleton.getInstance(); String somedata = model.getSomeData(); } } public class B { String name; public String getName() { return name; } public String doSomethingDifferentWithSharedData(){ MySingleton model = MySingleton.getInstance(); String somedata = model.getSomeOtherData(); } } 
0
source

Source: https://habr.com/ru/post/1240564/


All Articles