[factory mode] of the 23 design modes [creative mode] in Java

Design pattern classification

  • Create mode
    • Singleton mode, factory mode, abstract factory mode, builder mode, prototype mode
    • Creation process of object of interest
  • Structural mode
    • Adapter mode, bridge mode, decoration mode, combination mode, appearance mode, element sharing mode and agent mode
    • Focus on the organization of objects and classes
  • Behavioral model
    • Template method mode, command mode, iterator mode, observer mode, mediation mode, memo mode, interpreter mode, state mode, policy mode, responsibility chain mode and visitor mode
    • Pay attention to the interaction between the system and objects, study the mutual communication and cooperation between objects during the operation of the system, and further clarify the responsibilities of objects

Factory mode

  • It realizes the separation of creator and caller
  • Detailed classification:
    • Simple factory mode (most commonly used)
    • Factory method model
    • Abstract factory pattern
  • Basic principles of object-oriented design
    • OCP (open closed principle): a software entity should be open to extensions and closed to modifications
    • Dip (dependency inversion principle): it should be programmed for the interface, not for the implementation
    • LOD (Law of Demeter): only communicate with your direct friends and avoid communicating with strangers
  • Core essence
    • Instantiate the object and replace the new operation with the factory method
    • Implementation classes will be selected and objects created for unified management and control. This decouples the caller from our implementation class

Plant mode classification:

  • Simple factory mode
    • It is used to produce any product in the same hierarchical structure. (for adding new products, the existing code needs to be modified)
  • Factory method model
    • It is used to produce fixed products in the same hierarchical structure. (any product can be added)
  • Abstract factory pattern
    • Used to produce all products of different product families. (there is nothing you can do to add new products; support adding product families)

Comparison between simple factory model and factory method model

  • Structural complexity
    • From this perspective, it is obvious that the simple factory model is dominant. The simple factory mode only needs one factory class, while the factory class of the factory method mode increases with the increase of the number of product classes, which will undoubtedly increase the number of classes and increase the complexity of the structure.
  • Code complexity (simple factory pattern complexity)
    • Code complexity and structure complexity are a pair of contradictions. Since the simple factory pattern is relatively simple in structure, it must be more complex in code than the factory method pattern. With the increase of product classes, factory classes in simple factory mode need to add many methods (or codes), while each specific factory class in factory method mode only completes a single task, and the code is simple.
  • Difficulty of client programming (simple factory)
    • Although the factory method pattern introduces an interface into the factory class structure to meet OCP, it needs to instantiate the factory class in the client-side coding. The factory class of simple factory pattern is a static class, which does not need to be instantiated on the client, which is undoubtedly an attractive advantage
  • Management difficulty
    • From the perspective of scalability: both have good scalability, although the simple factory mode does not fully meet OCP
    • From the perspective of Maintainability: when multiple product classes need to be modified, the modification of factory classes will become quite troublesome; Instead, the simple factory model only needs to change the only factory class (can it be changed to meet the requirements anyway? It's a big deal to rewrite this class)
  • Recommendations:
    • According to the suggestion of design theory: factory method mode
    • Actual development: generally use simple factory mode

Simple factory mode

main points

  • Simple factory mode is also called static factory mode because factory classes generally use static methods to return different object instances through different received parameters
  • There is nothing you can do to add new products. If you can't modify the code, you can't expand it

code

  • Interface

    public interface Car {
    	void run();
    
    }
    
  • Specific class (Audi, Byd)

    //Audi class
    package simplefactory;
    
    public class Audi implements Car{
    
    	@Override
    	public void run() {
    
    		System.out.println("Audi run again");
    	}
    
    }
    //-----------------------------------------------------------------
    //Byd class
    package simplefactory;
    
    public class Byd implements Car{
    
    	@Override
    	public void run() {
    
    		System.out.println("BYD will run again");
    	}
    
    }
    
    
  • Factory type writing method I:

    package simplefactory;
    
    public class CarFactory {
    
    	public static Car creatCar(String type) {
    		if("audi".equals(type)) {
    			return new Audi();
    		}else if("BYD".equals(type)) {
    			return new Byd();
    		}else {
    			return null;
    		}
    	}
    }
    
    
  • Factory type writing method II

    package simplefactory;
    
    public class CarFactory2 {
    
    	public static Car createAudi() {
    		return new Audi();
    	}
    	public static Car createByd() {
    		return new Byd();
    	}
    }
    
    
  • Factory type writing method 3:

    package simplefactory;
    
    public class CarFactory3 {
    
    	public static Car createCar(String type) {
    		Car c = null;
    		if("audi".equals(type)) {
    			c = new Audi();
    		}else if("BYD".equals(type)) {
    			c = new Byd();
    		}
    		
    		return c;
    	}
    }
    
    
  • Caller:

    package simplefactory;
    //Use factory class I
    public class Client02 {
    
    	public static void main(String[] args) {
    		Car c1 = CarFactory.creatCar("audi");
    		Car c2 = CarFactory.creatCar("BYD");
    		 
    		c1.run();
    		c2.run();
    		
    	}
    }
    
    

Factory method model

main points:

  • In order to avoid the disadvantages of simple factory mode, OCP is not fully satisfied
  • The biggest difference between the factory method pattern and the simple factory pattern is that the simple factory pattern has only one factory class (for a project or an independent module), while the factory method pattern has a group of factory classes that implement the same interface

code

  • Vehicle interface and factory interface

    //Automobile interface, specification, automobile model
    package factorymethod;
    
    public interface Car {
    	void run();
    
    }
    
    //Factory interface specification
    package factorymethod;
    
    public interface CarFactory {
    
    	Car createCar();
    }
    
    
    
  • Automobile and factory

    //Automobile
    package factorymethod;
    
    public class Audi implements Car{
    
    	@Override
    	public void run() {
    
    		System.out.println("Audi run again");
    	}
    
    }
    
    //Factory class corresponding to automobile
    package factorymethod;
    
    public class AudiFactory implements CarFactory{
    
    	@Override
    	public Car createCar() {
    		return new Audi();
    	}
    
    }
    
    
  • caller

    package factorymethod;
    
    public class Client {
    	public static void main(String[] args) {
    		Car c1 = new AudiFactory().createCar();//Create a car through the factory
    		c1.run();
    	}
    
    }
    
    
    

Application:

Every time a new thing is added, it is necessary to create a class of the thing and a factory class that can create the object of the thing

The caller creates the corresponding object through the corresponding factory

Abstract factory pattern

main points

  • Used to produce all products of different product families. (there is nothing you can do to add new products; support adding product families)

  • Abstract factory pattern is an upgraded version of factory method pattern. When there are multiple business varieties and business classifications, it is a very good solution to produce the required objects through abstract factory pattern

    enginechairtyre——>A product family
    High end engineHigh end seatsHigh end tire
    Low end engineLow end seatLow end tire

code

Each product in the product family corresponds to:

  • Abstract class (product model)
  • Product realization class (specific realization)

Factory:

  • Abstract factory class (rules for factory to create products)
  • Factory implementation (produce products according to rules)

Caller:

  • Create the required factory through the factory interface
  • Through the corresponding product interface, products are produced in the created factory
  • Engine abstract class and implementation class

    //Engine abstract class
    package abstractFactory;
    
    public interface Engine {
    
    	void run();
    	void start();
    }
    
    //Implementation class of engine (LuxuryEngine high-end engine, LowEngine low-end engine)
    class LuxuryEngine implements Engine{
    
    	@Override
    	public void run() {
    		System.out.println("High end engine, fast rotation");
    	}
    
    	@Override
    	public void start() {
    		System.out.println("High end engine, start fast! It can start and stop automatically");
    	}
    	
    }
    class LowEngine implements Engine{
    	
    	@Override
    	public void run() {
    		System.out.println("The low-end engine turns slowly");
    	}
    	
    	@Override
    	public void start() {
    		System.out.println("Low end, slow start! Automatic start and stop is not allowed");
    	}
    	
    }
    
    
    
  • Seat abstract class and implementation class

    //Seat abstract class
    package abstractFactory;
    
    public interface Seat {
    	
    	void massage();
    	
    }
    
    //Seat realization class (LuxurySet high-end seat, LowSeat low-end seat)
    class LuxurySeat implements Seat{
    
    	@Override
    	public void massage() {
    		System.out.println("High end, automatic massage");
    	}
    	
    }
    class LowSeat implements Seat{
    	
    	@Override
    	public void massage() {
    		System.out.println("Low end, no automatic massage");
    	}
    	
    }
    
    
    
  • Tire abstract class and implementation class

    //Tire abstract class
    package abstractFactory;
    
    public interface Tyre {
    
    	void revolve();
    }
    
    //Implementation of tires (LuxuryTyre high-end tires, LowTyre low-end tires)
    class LuxuryTyre implements Tyre{
    
    	@Override
    	public void revolve() {
    		System.out.println("High end, no wear during rotation");
    	}
    
    
    	
    }
    class LowTyre implements Tyre{
    
    	@Override
    	public void revolve() {
    		System.out.println("Low end, rotating wear");
    	}
    	
    	
    	
    }
    
    
    
  • Factory abstract class

    package abstractFactory;
    
    public interface CarFactory {
    	Engine createEngine();
    	Seat createSeat();
    	Tyre createTyre();
    
    }
    
    
    
  • Factory realization (high-end factory and low-end factory)

    //High end factory implementation
    package abstractFactory;
    
    public class LuxuryCarFactory implements CarFactory{
    
    	@Override
    	public Engine createEngine() {
    		return new LuxuryEngine();
    	}
    
    	@Override
    	public Seat createSeat() {
    		return new LuxurySeat();
    	}
    
    	@Override
    	public Tyre createTyre() {
    		return new LuxuryTyre();
    	}
    
    }
    
    //Low end factory implementation class
    package abstractFactory;
    
    public class LowCarFactory implements CarFactory{
    
    	@Override
    	public Engine createEngine() {
    		return new LowEngine();
    	}
    
    	@Override
    	public Seat createSeat() {
    		return new LowSeat();
    	}
    
    	@Override
    	public Tyre createTyre() {
    		return new LowTyre();
    	}
    
    }
    
    
    
  • client:

    package abstractFactory;
    
    public class Client {
    
    	public static void main(String[] args) {
    		CarFactory factory = new LuxuryCarFactory();
    		Engine e = factory.createEngine();
    		e.run();
    		e.start();
    	}
    }
    //Results————————————————————————————————————————————————————————————
    High end engine, fast rotation
     High end engine, start fast! It can start and stop automatically
    
    

summary

  • Key points of factory mode:
    • Simple factory mode (static factory mode)
      • Although it does not conform to the design principles to some extent, it is actually used most
    • Factory method model
      • Without modifying the existing class, the extension can be realized by adding a new factory class
    • Abstract factory pattern
      • Products cannot be added, but product families can be added
  • Application scenario
    • getInstance method of Calendar in JDK
    • Acquisition of Connection object in JDBC
    • Create a Session using SessionFactory in Hibernate
    • Creating management bean objects from IOC container in spring
    • Create parser for DocumentBuilderFactory during XML parsing
    • newInstance() of Class object in reflection

Tags: Java Big Data Programming Design Pattern

Posted by SQL Maestro on Mon, 18 Apr 2022 15:30:30 +0930