It is generally divided into simple factory, static factory, factory method and abstract factory.

A simple factory is a simple factory as long as it returns only one thing, static factory methods are static and can be combined with singletons

Factory Method:

Create a factory method class for each class you create, such as DogFactory for Dog and CatFactory for Cat

Public class DogFactoryMethod {public static Dog create(){return new Dog(); }}Copy the code

Abstract factory:

This guy is a product guy, Dog, Dog toys, food… Cat has Cat toys, Cat food… Let’s start with an abstract factory class

Public abstract class AbstractFactory {abstractfood createFood(); public abstract class AbstractFactory {abstractfood createFood(); abstract Toy createToy(); }Copy the code

Abstract product class:

public abstract class Food {
    abstract void foodName();
}
Copy the code
public abstract class Toy {
    abstract void printName();
}
Copy the code

Specific products:

Public class extends Food {@override void foodName() {system.out.println (" Apple "); }}Copy the code
Public class extends Food {@override void foodName() {system.out.println (" Fish "); }}Copy the code
Public class Clew extends Toy{@override void printName() {system.out.println (); public class Clew extends Toy{@override void printName() {system.out.println (); }}Copy the code
Public class Tone extends Toy {@override void printName() {system.out.println (" bone "); }}Copy the code

Specific factory:

public class CatFactory extends AbstractFactory { @Override Food createFood() { return new Fish(); } @Override Toy createToy() { return new Clew(); }}Copy the code
public class DogFactory extends AbstractFactory { @Override Food createFood() { return new Apple(); } @Override Toy createToy() { return new Tone(); }}Copy the code

Specific use:

Public class Test1 {public static void main(String[] args) {// DogFactory DogFactory = new DogFactory(); Food food = dogFactory.createFood(); Toy toy = dogFactory.createToy(); // CatFactory CatFactory = new CatFactory(); Food food1 = catFactory.createFood(); Toy toy1 = catFactory.createToy(); }}Copy the code

Two questions:

1. When an abstract factory has only one product in its product cluster, it almost degenerates into a factory method
2. Why do these classes in the abstract factory use abstract classes instead of interfaces

Of course you can do things with interfaces, but things like Food and Toy are things that are best designed as abstract classes, properties of things that are best designed as interfaces. In a simple word, nouns are designed as abstract classes, adjectives are designed as interfaces, and adjectives can be combined indefinitely.