Design mode 4 factory mode of multi factories

Multi factory mode

When we do a more complex project, we often encounter the situation that it takes a lot of energy to initialize an object. All product classes are initialized in a factory method, which makes the code structure unclear.
Considering the need for clear structure, we define a creator for each product, and then the caller will choose which factory method to associate with.

uml class diagram

Realization

  1. Abstract factory class AbstractMultiMachineFactory.java
public abstract class AbstractMultiMachineFactory {
   abstract public Machine createMaching();
}
  1. Specific factory

Bicycle factory

BikeFactory.java

public class BikeFactory extends AbstractMultiMachineFactory{
    @Override
    public Machine createMaching() {
        return new Bike();
    }
}

Car factory

CarFactory.java

public class CarFactory extends AbstractMultiMachineFactory{
    @Override
    public Machine createMaching() {
        return new Car();
    }
}

Truck factory

TruckFactory.java

public class TruckFactory extends AbstractMultiMachineFactory{
    @Override
    public Machine createMaching() {
        return new Truck();
    }
}

Product category immovable

Design mode 2 factory method mode

Customer test

public class ClientTest {
    @Test
    public void createMachine(){
        // Containers packed to customers
        List<Machine> list = new ArrayList<>() ;

        /**
         * 1.Customers place orders and start building cars (2 cars, 2 trucks, 2 bicycles)
         */
        // Automobile production line
        CarFactory carFactory = new CarFactory() ;
        for(int i=0;i<2;i++){
            list.add(carFactory.createMaching());
        }
        // Truck production line
        TruckFactory truckFactory = new TruckFactory() ;
        for(int i=0;i<2;i++){
            list.add(truckFactory.createMaching());
        }
        // Bicycle production line
        BikeFactory bikeFactory = new BikeFactory() ;
        for(int i=0;i<2;i++){
            list.add(bikeFactory.createMaching());
        }

        //The customer begins to test the performance of each vehicle
        list.forEach(ele -> {
            ele.start() ;
            ele.speed();
            ele.stop();
            if(ele instanceof Car){
                ((Car) ele).blow();
            }
            if(ele instanceof Truck){
                ((Truck) ele).blow();
            }
        });
    }
}

Source code

Singleton mode

Simple factory mode

Factory method mode

Blog series

One example of design pattern

Design mode 2 factory method mode

Design mode 3: simple factory mode

Keywords: Java

Added by Woolf on Thu, 30 Apr 2020 09:04:06 +0300