简体   繁体   中英

Design Pattern for java threading

I have a background service that has a thread running every 15 seconds and doing some work.

public class CacheCleaner implements Runnable, BackgroundService {
    ....

    @Override
    public void run() {
      ....
    }
}

BackgroundService is another interface that I have defined with methods that I want every background service in the system to implement.

public interface BackgroundService
{
   String getName();
   void start(long initialDelay);
   .....
}

The problem is that I want to do some work (3-4 lines of basic code) in the run method of every such class (there are 10-15 of them). Is there a design pattern or any better way I can achieve this rather than copy pasting the 4 lines in each of the 15 run methods?

NOTE: I mention the run() method since I only want those 4 lines of code to be executed when the thread is active.

You can use inheritance ... for example,

public abstract class AbstractBaseRunnable implements Runnable {
    ...
    @Override
    public void run() {
        ... // base work here!
    }
}

public class CacheCleaner extends AbstractBaseRunnable implements BackgroundService {
    ...
    @Override
    public void run() {
        super.run();
        ... // particular work for CacheCleaner here!!
    }
}

I guess you can do something similar to this.

public abstract class Task implements Runnable {

 @Override
 void run() {
  //do ur common stuff here (3-4 lines of code that u mentioned)
  execute();
 }
 public abstract void execute();

}

You implement the Runnable/Callable whichever you like/need. In above code "Task" class implements the Runnable and also implements the "run()" method. Here in "run()" method you can do whatever common stuff you want to do and declare a abstract method "execute()" which can be implemented by the implementation classes based on the need. Your "CacheCleaner" will look like this:

public class CacheCleaner extends Task implements BackgroundService {
 ....

 @Override
 public void execute() {
  ....
 }
}

You could make an abstract class containing your 3-4 lines of basic code and every of you 10-15 background services subclassing it.

public abstract class AbstractBackgroundService implements Runnable,BackgroundService{

    @Override
    public final void run() {
        prepareRun();

        runImpl(); 
    }

    private void prepareRun() {
        // your 3-4 lines basic code
    }

    protected abstract void runImpl();
}

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