Detailed Factory Mode (2)-Factory Method Mode

1. Factory method pattern

The factory method pattern (Fatory Method Pattern) refers to the definition of an interface for creating objects, but let the class that implements this interface decide which class to instantiate, and the factory method delays the instantiation of the class to the subclass. In the factory method mode, the user only needs to care about the factory corresponding to the required product, and does not need to care about the creation details, and adding new products conforms to the principle of opening and closing.

2. Application

The factory method model mainly solves the problem of product expansion. In a simple factory, with the enrichment of the product chain, if the creation logic of each course is different, the responsibilities of the factory will become more and more, a bit like a universal factory, and It is not easy to maintain. According to the single responsibility principle, we will continue to split the functions and assign people to do special tasks. The Java course is created by the Java factory, and the Python course is created by the Python factory, which also abstracts the factory itself.

3. Code implementation

3.1 Create ICourseFactory interface first

public interface ICourseFactory {
    
    
      ICourse create();
}

3.2 Create sub-factories, JavaCourseFactory class

import com.cc.vip.pattern.factory.JavaCourse;
public class JavaCourseFactory implements ICourseFactory {
    
     
	public ICourse create() {
    
    
		return new JavaCourse();
	}
}

3.3 PythonCourseFactory class:

import com.cc.vip.pattern.factory.ICourse; 
import com.gupaoedu.vip.pattern.factory.PythonCourse;

public class PythonCourseFactory implements ICourseFactory {
    
     
	public ICourse create() {
    
    
		return new PythonCourse();
	}
}

3.4 Test code

public static void main(String[] args) {
    
    
	ICourseFactory factory = new 
	PythonCourseFactory();
	ICourse course = factory.create();
	course.record();
	factory = new JavaCourseFactory();
	course = factory.create();
	course.record();
}

4. Class diagram

Regarding the application of the factory method pattern in logback, it is OK to look at the class diagram.

Insert picture description here
Insert picture description here
Insert picture description here

5. Summary

5.1 Application scenarios of factory method
  1. Creating objects requires a lot of repetitive code.
  2. The client (application layer) does not depend on the details of how the product class instance is created and implemented.
  3. A class specifies which object to create through its subclasses.
5.2 Disadvantages
  • The number of classes is easy to be too many, increasing complexity.
  • Increased the abstraction and difficulty of understanding the system.

Guess you like

Origin blog.csdn.net/weixin_46822085/article/details/108859255