Factory introduction of

First of all, we have a food class to produce different products

public abstract class Food {
	public void eat(a);
}
Copy the code

And then add two subclasses

public class Bread extends Food{
	@Override
	public void eat(a) {
		System.out.println("mianbao"); }}Copy the code
public class MushRoom extends Food{
	@Override
	public void eat(a) {
		System.out.println("Mushroom"); }}Copy the code

And then test the code

public static void main(String[] args) {
		Food food=new Bread();
		food.eat();
	}
Copy the code

In this case, if I want to produce flour and new bread and new bread and other things

But there is a problem. If I want to customize some configurations in the production process, I will be in trouble. Yes, I have to write the configurations for new, otherwise I will put them into the factory and take them out directly after they are configured.

Simple factory

public class SimpleFactory {


	public Bread createBread(a){
		// Custom configuration
		return new Bread();
	}
	public MushRoom createMushRoom(a){
		// Custom configuration
		return newMushRoom(); }}Copy the code

This is convenient, but there is also a problem, is every time to the inside of the class to write, to extend his attributes and methods is very troublesome, easy chaos. You can imagine if a class had 10 methods and there were 1000 classes to produce that would be an explosion.

The factory method

It’s one factory per class and you can extend it as much as you want

The abstract factory

Because the factory method is a little bit tricky when you have more than one product being produced in a factory, so what we need to do is we need to write a big abstract factory, write the abstract product that we want to produce, and if we use the factory method to inherit and implement it, then we can just call the factory.