Biography: Swing unruly, love life. Java Cultivator (wechat official ID: Java Cultivator), welcome to follow. Access to 2000G of detailed information on the 2020 interview questions

JAVA has 23 design patterns. The factory method pattern and abstract factory method are among the creation patterns. The 23 design patterns are shown in the following figure:

This time I will focus on the factory method pattern and abstract factory method.

As for Factory methods, simple Factory, Factory Method and Abstract Factory are generally mentioned. In GOF’s Book Design Patterns, Factory patterns are divided into two categories: Factory Method and Abstract Factory. Consider the Simple Factory pattern as a special case of the Factory method pattern, and the two fall into the same category.

A, definitions,

  • Simple Factory pattern ** (Simple Factory) ** : Define a class that is responsible for creating instances of other classes, often with a common parent class.

  • Factory Method pattern ** (Factory Method) ** : Defines an interface for creating objects and lets subclasses decide which class to instantiate. The factory method delays the instantiation of a class to its subclasses

  • Abstract Factory pattern ** : Provides an interface to create a series of related or interdependent objects without specifying their concrete classes.

Second, the difference between

Factory method pattern: An abstract product class that can be derived from multiple concrete product classes. An abstract factory class can be derived from multiple concrete factory classes. Only one instance of a concrete product class can be created per concrete factory class. Abstract Factory pattern: Multiple abstract product classes, each of which can derive multiple concrete product classes. An abstract factory class can be derived from multiple concrete factory classes. Each concrete factory class can create multiple instances of a concrete product class. Difference: The factory method pattern has only one abstract product class, while the Abstract factory pattern has multiple. The concrete factory class of the Factory method pattern can create only one instance of a concrete product class, whereas the abstract factory pattern can create multiple instances.

Three, code actual combat description

1. Simple Factory mode

Store.java

Frute a= factory.getfrute ("apple"); if(a! =null) System.out.println(a.tell()); Frute b= factory.getfrute ("banana"); if(a! =null) System.out.println(a.tell()); }} public static Frute getFrute(String name){ if(name.equals("apple")){ return new Apple(); } else if(name.equals("banana")){ return new Banana(); } return null; } } Frute.javapublic interface Frute{ public String tell(); Javapub lic class Apple implements Frute{public String tell(){return "I am Apple "; Javapublic class Banana implements Frute{public String implements Frute (){return "I am a Banana "; }}Copy the code

Advantages: The simple factory pattern can determine which concrete class objects should be created based on information given from the outside world. It clearly distinguishes their responsibilities and powers, which is conducive to the optimization of the entire software architecture.

Disadvantages: It’s obvious that the factory class centralizations the creation logic of all instances, and it’s easy to violate GRASPR’s highly cohesive assignment of responsibility. Adding a Grape class, for example, doesn’t require changes to other product classes, such as Apple and Banana. So the simple factory pattern does not conform to the OCP principle.

2. Factory mode

Javapublic interface Shape {oid draw(); } // Create an entity class that implements the interface. Rectangle.javapublic class Rectangle implements Shape { @Override public void draw() { System.out.println("Inside Rectangle::draw() method."); } } Square.javapublic class Square implements Shape { @Override public void draw() { System.out.println("Inside Square::draw() method."); } } Circle.javapublic class Circle implements Shape { @Override public void draw() { System.out.println("Inside Circle::draw() method."); }} // Create a factory that generates objects based on the entity class given the informationCopy the code

ShapeFactory.java

Public class ShapeFactory {public Shape getShape(String shapeType){if(shapeType == null){ return null; } if(shapeType.equalsIgnoreCase("CIRCLE")){ return new Circle(); } else if(shapeType.equalsIgnoreCase("RECTANGLE")){ return new Rectangle(); } else if(shapeType.equalsIgnoreCase("SQUARE")){ return new Square(); } return null; }} // Use this factory to get the object of the entity class by passing type information. FactoryPatternDemo.javapublic class FactoryPatternDemo { public static void main(String[] args) { ShapeFactory shapeFactory = new ShapeFactory(); Shape1 = shapeFactory.getShape(" Circle "); shapeFactory.getShape(" Circle "); // Call Circle's draw method shape1.draw(); Shape2 = ShapeFactory. getShape(" Rectangle "); // Rectangle = ShapeFactory. getShape(" Rectangle "); // Rectangle = ShapeFactory. getShape(" Rectangle "); // Call Rectangle's draw method shape2.draw(); Shape3 = shapeFactory.getShape(" Square "); shapeFactory.getShape(" Square "); // call Square's draw method shape3.draw(); }}Copy the code

Validation output:

Inside Circle::draw() method.   
 Inside Rectangle::draw() method.   
 Inside Square::draw() method.
Copy the code

In fact, the above can be used to solve the problem of adding an implementation factory each time a product is added.

As follows:

Shapefactory.java (Rewrite factory)

public class ShapeFactory {   
 public static Object getClass(Class<?extends Shape> clazz) {     
   Object obj = null;     
   try
 {          
  obj = Class.forName(clazz.getName()).newInstance();      
  } 
catch (ClassNotFoundException e) {       
     e.printStackTrace();    
    }
 catch (InstantiationException e) {      
      e.printStackTrace();     
   } 
catch (IllegalAccessException e) {       
     e.printStackTrace();      
  }      
  return obj;  
  }
}
Copy the code

make

Use cast when using:

Rectangle rect = (Rectangle) ShapeFactory.getClass(Rectangle.class);
rect.draw();
Square square = (Square) ShapeFactory.getClass(Square.class);
square.draw();
Copy the code

Abstract factory pattern

Engine.javapublic interface Engine{} enginea. javapublic class EngineA extends Engine{public EngineA(){ System. Out. Println (" manufacturing - > EngineA "); }} engineb. Java public class EngineB extends Engine{public EngineB(){system.out.println (" make -->EngineB"); Aircondition. Javapublic interface Aircondition {} Aircondition. Javapublic class AirconditionA extends Aircondition{public conditiona (){system.out.println (" make -->AirconditionA"); } } AirconditionB.javapublic class AirconditionB extends Aircondition{ public AirconditionB(){ System. Out. Println (" manufacturing - > AirconditionB "); Abstractfactory.javapublic interface AbstractFactory {public Engine createEngine(); Public Aircondition createAircondition(); Java public class FactoryBMW320 implements AbstractFactory{@override public Engine createEngine() { return new EngineA(); } @Override public Aircondition createAircondition() { return new AirconditionA(); Class FactoryBMW523 implements AbstractFactory {@override public Engine createEngine() { return new EngineB(); } @Override public Aircondition createAircondition() { return new AirconditionB(); }} Customer :public class Customer {public static void main(String[] args) FactoryBMW320(); factoryBMW320.createEngine(); factoryBMW320.createAircondition(); FactoryBMW523 = New FactoryBMW523(); factoryBMW320.createEngine(); factoryBMW320.createAircondition(); }}Copy the code

Advantages: When multiple objects in a product family are designed to work together, it ensures that the client always uses only objects in the same product family.

Disadvantages: Product family extension is very difficult. To add a product in a series, you need to add code in both the abstract Creator and the concrete one.

Note: Product family is difficult to expand, product level is easy to expand.

Applications in Spring

1, JDBC used in the system: the client through the data operation factory, the use of JDBC interface, to achieve different database system objects, according to the specific database type (mysql, Oracledeng), using different JDBC

The Spring framework’s Ioc container beanFactory: generates and manages beans

Five, the summary

Whether it is simple factory pattern, factory method pattern, or abstract factory pattern, they all belong to factory pattern and are very similar in form and characteristics. Their ultimate goal is decoupling.

(1) Simple factory mode is a concrete class to create instances of other classes, the parent class is the same, the parent class is concrete. (2) The factory method pattern has an abstract parent class defining the public interface, the child class is responsible for generating concrete objects, the purpose of this is to defer the class instantiation operation to the child class to complete. (3) The abstract factory pattern provides an interface to create a series of related or interdependent objects without specifying their concrete classes. It targets hierarchical structures with multiple products. The factory method pattern targets the hierarchical structure of a product.

When using the factory pattern, you only need to care if the goal of reducing coupling is achieved.

Sharing personal study notes recently organized into a book, using PDF sharing mainly includes Java foundation, data structure, JVM, multithreading and so on, due to the space is limited, the following only show a small part of the interview questions, need friends can point to get: Poke here can get…

Point attention, don’t get lost; Keep updating Java related technology and information!!