Factory pattern

The factory pattern is interface or class for creating objects. Client works with created objects through defined interface or base class.

problems

Suppose we have a logic that needs to create some objects for its work. For example, the ThreadPoolExecutor class in Java must create Thead objects to execute tasks. But what to do if the threads must have other configuration or we need use derived class?

If we change the logic to support a different configuration, this will pollute the code, and we cannot be sure that another configuration will not appear in the future.

We can also write each time a derived class that will create the necessary objects in the factory method. But it also may not be very readable. For example, if the difference is only in factory method then how we name new class? ThreadPoolExecutorWithMythread1?

The best decision is to put the task of creating objects in a separate object and pass it to our logic as a parameter.

advantages

  • Reduce dependency.
  • More pretty code.
// from Java source 
// interface for creation Thread objects
public interface ThreadFactory {
    Thread newThread(Runnable r);
}

// java doc example
public  class SimpleThreadFactory implements ThreadFactory {
    public Thread newThread(Runnable r) {
        return new Thread(r);
    }
}

// using
ExecutorService exeSrv1 =
    Executors.newCachedThreadPool((r) -> new Thread(r));

ExecutorService exeSrv2 =
    Executors.newCachedThreadPool(new SimpleThreadFactory());