简体   繁体   中英

Modelling actions in Java

I am looking to standardize common actions using a design pattern but I am not sure which one is the best.

Let's say if we start off with two service Java classes with two operations/methods each.

class Service1 {
    public void performSomething() {
        // Some complex algorithm implemented here
    }
    public void performSomethingElse {
        // Some complex algorithm implemented here
    }
}

class Service2 {
    public void performSomething() {
        // Some complex algorithm implemented here
    }
    public void performSomethingElse {
        // Some complex algorithm implemented here
    }
}

Two services are sharing the same algorithms so naturally, I would want to refactor performSomething() and performSomethingElse() . My approach is to create two single-method classes for each refactored method.

interface Action {
    public void run();
}
class PerformSomething implements Action {
    public void run() {}
}
class PerformSomethingElse implements Action {
    public void run() {}
}

class Service1 {
    private PerformSomething algo1;
    private PerformSomethingElse algo2;

    public void businessUseCase1() {
        algo1.run();
        algo2.run();
    }

}

I feel like this simple approach is naive and I am very sure there's a more suitable design pattern that can represent an Action instead of creating a custom interface to present Actions.

With KISS and Spring in mind, I would just do the following:

@Service
class Service1 {
    public void performSomething() {
        // Some complex algorithm implemented here
    }
    public void performSomethingElse {
        // Some complex algorithm implemented here
    }
    public void businessUseCase1() {
        performSomething();
        performSomethingElse();
    }

}

@Service
class Service2 {
    @Autowired
    Service1 service1;

    public void performSomething() {
        // Some complex algorithm implemented here
    }
    public void performSomethingElse {
        // Some complex algorithm implemented here
    }
    public void businessUseCase1() {
        service1.performSomething();
        service1.performSomethingElse();
        // or
        service1.businessUseCase1();
    }

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM