In the section of simple factory mode, the simple factory mode is introduced, and it is mentioned that the simple factory mode violates the open and close principle, and the “factory method mode” is a further abstraction of the simple factory mode. Its advantage is that the system can introduce new products without modifying the original code, that is, to meet the open and close principle.

Structure and implementation of patterns


Factory method pattern consists of abstract factory, concrete factory, abstract product and concrete product. This section analyzes its basic structure and implementation method.

  1. The main roles of the factory method pattern are as follows.
  • Abstract Factory: Provides an interface for creating products through which callers create products by accessing the Factory method newProduct() of a concrete Factory.
  • ConcreteFactory: Abstract methods in abstract factories are implemented to create concrete products.
  • Abstract Product: Defines the specification of the Product, describing the main features and functions of the Product.
  • Concreteproducts: Interfaces that implement abstract product roles are created by concrete factories and correspond to concrete factories.

Structure class diagram:

Code sample


  • Abstract Product
public abstract class Mobile {
    /** * show mobile info */
	public abstract void show(a);
}
Copy the code
  • ConcreteProduct Concrete products
public class Huawei extends Mobile{
	public void show(a) {
		System.out.println("huawei P40 mobile"); }}public class Iphone extends Mobile {
	public void show(a) {
		System.out.println("apple iphone mobile"); }}Copy the code
  • Abstract Factory Abstract Factory
public abstract class AbstractFactory {
	
    public abstract Mobile product(a);
}
Copy the code
  • ConcreteFactory ConcreteFactory
public class AppleConcreteFactory extends AbstractFactory{

	@Override
	public Mobile product(a) {
		return newIphone(); }}public class HuaweiConcreteFactory extends AbstractFactory {

	@Override
	public Mobile product(a) {
		return newHuawei(); }}Copy the code
  • Use the client
public class Client {
	public static void main(String[] args) {
		AbstractFactory abstractFactory = newAppleConcreteFactory(); Mobile mobile = abstractFactory.product(); mobile.show(); }}Copy the code

Execution Result:

apple iphone mobile
Copy the code
  • Use client2
public static void main(String[] args) throws ClassNotFoundException, InstantiationException, IllegalAccessException {
		// Specify factory class information
        String factoryName = "com.edu.factory.method.AppleConcreteFactory";
        // Get the factory class through reflection
        Class c = Class.forName(factoryName);
        AbstractFactory factory = (AbstractFactory)c.newInstance();
        // Display the product
        Mobile mobile = factory.product();
        mobile.show();
	}
Copy the code

The execution result

huawei P40 mobile
Copy the code

Code case class diagram:

The advantages and disadvantages


Advantages:

  • Users only need to know the name of the specific factory to get the product they want, without knowing the specific creation process of the product.
  • Increased flexibility, for the creation of new products, only need to write a corresponding factory class.

A typical decoupling framework.

  • A high-level module only needs to know the abstract class of the product and does not need to care about other implementation classes, satisfying Demeter’s law, dependency inversion principle and Richter’s substitution principle.

Disadvantages:

  • It is easy to have too many classes and add complexity
  • The system is abstract and difficult to understand
  • Abstract products can only produce one product, this disadvantage can be usedAbstract Factory patternTo solve.

Application scenarios


  • The customer only knows the name of the factory that created the product, not the specific product name. Such as Huawei mobile phone factory Apple mobile phone factory.
  • The task of creating an object is done by one of several concrete sub-factories, whereas an abstract factory provides only an interface to create a product.
  • Customers don’t care about the details of creating a product, just the brand of the product

Typical application of factory method pattern and source code analysis


  • The factory method in Logback uses an abstract factory forILoggerFactory interface, the factory method isgetLogger(), the specific role of the factory isLoggerContext,NOPLoggerFactory,SubstituteLoggerFactoryAnd so on.
public interface ILoggerFactory {
    public Logger getLogger(String name);
}
Copy the code

Specific factory roleThe abstract product role isLogger, the specific product role isLoggerImplementation class:Here is a screenshot directly from my own project package, and you can see that there are many implementation classesslf4j,kafkaAll have. Here toLoggerContextAs a concrete factory, its entire structure class diagram is as follows:

✨✨ welcome 🔔 to subscribe to your wechat account for blog updates✨✨ Personal GitHub address