How to handle common classes / interfaces in a modular application?

I am new to Java and coding a modular application made like this:

*************          *******         ***********
*           *          *     *         *   Data  *
* Front-end * -------- * API * ------- * Handler *
*           *          *     *         *         *
*************          *******         ***********

Essentially, I want to be able to define an API with N classes, and then have a Data Handler module to store objects somewhere (for example, in a database), without the interface knowing anything about how this is implemented.

So, let's say I have two classes defined in my API: Contract and Company. I want the front-end to be able to do something like:

myContract = new Contract();
myCompany = new Company();
myContract.setCompany(myCompany);
myContract.save();
myCompany.save();

Thus, in the future, I could change the way data is stored (Data Handler module) without changing the code in the interface.

To do this, I wrote two interfaces for Contract and Company in the API module. Then, in the data processor module, I wrote classes that implement two interfaces: DbContract and DbCompany.

, getter/setter Contract :

public interface Contract {
    public Company getCompany();
    public void setCompany(Company company);
}

DbContract :

public class DbContract implements Contract {
    private DbCompany company;

    @Override
    public Company getCompany() {
        return this.company;
    }

    @Override
    public void setCompany(Company company) {
        this.company = company;
    }
}

, ... ? ?

.

+4
2
myContract = new Contract();

, .

, , , "".

, . , , .

, Contract Company , . :

class Contract { ... } //as before, but classes not interfaces
class Company { ... } //as before, but classes not interfaces

:

Contract myContract = new Contract();
Company myCompany = new Company();
myContract.setCompany(myCompany);

contractService.save( myContract ); //assuming this would save the company as well

. Spring.

:

, Company Contract JPA, , , - , JPA.

:

  • POJO XML JPA- . , .

  • , , ( = DTO), API. DTO.

+1

    private DbCompany company;

    private Company company;

.

, , . . - :

public interface Contract<T extends Company>{
    public T getCompany();
    public void setCompany(T company);
}

public class DbContract implements Contract<DbCompany> {
    private DbCompany company;

    @Override
    public DbCompany getCompany() {
        return this.company;
    }

    @Override
    public void setCompany(DbCompany company) {
        this.company = company;
    } 
}
+2

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


All Articles