[learning notes] factory mode

Keywords: Java Design Pattern

0 design mode

If you don't know about design patterns, you can first understand what design patterns are through this article

https://blog.csdn.net/qq_42874315/article/details/120006447?spm=1001.2014.3001.5502

1 factory mode

The creative design mode is mainly used to create objects. It replaces us to complete the operation of new objects and gives them to the factory to create and manage objects, which is conducive to reducing the coupling degree of code and improving the scalability of code, and we can flexibly control the production process of objects. Any method or class that can produce an object can be called a factory.

Factory patterns are divided into two categories: factory methods and abstract factories.

2 implementation ideas

2.1 realization idea of factory method

We will create a Moveable interface and an entity class that implements the Moveable interface.

The next step is to define the factory classes CarFactory and CarFactory.

The Test class uses CarFactory to obtain the Car object and PlaneFactory to obtain the Plane object

2.2 implementation idea of abstract factory

Create an abstract factory, which is inherited by the sub factory, and create a specific Abstract implementation through the sub factory, so as to realize the expansion of a family. For example, in the figure below, the weapons and mobile tools produced by modern factory and magic factory are different

In the test class, create specific objects through the createXX() method of the sub factory

3 required classes

3.1 classes required for plant methods

  1. An interface abstracted from multiple concrete classes
  2. Specific implementation classes
  3. Simple factory

3.2 classes required for abstract methods

  1. Abstract factory (defines abstract methods and returns abstract classes)
  2. abstract class
  3. The implementation class that inherits the abstract class
  4. Factory method (inherit Abstract Factory)

4 specific implementation

4.1 realization of factory method

4.1.1 Moveable interface

public interface Moveable {
    void go();
}

4.1.2 implementation class of moveable interface

Car

public class Car implements Moveable{
    public void go() {
        System.out.println("Car go wuwuwuwuwu....");
    }
}

Plane

public class Plane implements Moveable{
    public void go(){
        System.out.println("plane flying shuashuashua........");
    }
}

4.1.3 simple factory

PlaneFactory

public class PlaneFactory {
    public Moveable create(){
        System.out.println("Log operation ===== a car created!! ");
        return new Plane();
    }
}

CarFactory

public class CarFactory {
    public Moveable create(){
        System.out.println("Log operation ===== a car created!! ");
        return new Car();
    }
}

4.1.4 testing

public class Main {
    public static void main(String[] args) {
        Moveable m = new CarFactory().create();
        m.go();
        Moveable moveable = new PlaneFactory().create();
        moveable.go();
    }
}

4.2 implementation of abstract factory

4.2.1 AbstractFactory

public abstract class AbstractFactory {
    abstract Food createFood();
    abstract Vehicle createVehicle();
    abstract Weapon createWeapon();
}

4.2.2 abstract classes

Vehicle

public abstract class Vehicle {
    abstract void go();
}

Weapon

public abstract class Weapon {
    abstract void shoot();
}

4.2.3 implementation class

Broom

public class Broom extends Vehicle{
    public void go(){
        System.out.println("Broom go shuashuashua.........");
    }
}

Car

public class Car extends Vehicle{
    public void go() {
        System.out.println("Car go wuwuwuwuwu....");
    }
}

AK47

public class AK47 extends Weapon{
    public void shoot(){
        System.out.println("Convex convex convex convex....");
    }
}

MagicStick

public class MagicStick extends Weapon {
    public void shoot(){
        System.out.println("diandian.....");
    }
}

4.2.4 factory method (inherit Abstract Factory)

ModernFactory

public class ModernFactory extends AbstractFactory {
    @Override
    Vehicle createVehicle() {
        return new Car();
    }

    @Override
    Weapon createWeapon() {
        return new AK47();
    }
}

MagicFactory

public class MagicFactory extends AbstractFactory {
    @Override
    Vehicle createVehicle() {
        return new Broom();
    }

    @Override
    Weapon createWeapon() {
        return new MagicStick();
    }
}

4.2.5 testing

public class Main {
    public static void main(String[] args) {
        // Modern factory
        AbstractFactory factory = new ModernFactory();
        factory.createVehicle().go();
        factory.createWeapon().shoot();
		// Magic factory
        AbstractFactory magicFactory = new MagicFactory();
        magicFactory.createVehicle().go();
        magicFactory.createWeapon().shoot();
    }
}

5 expansion

5.1 plant method extension

5.1.1 assumption of plant method

  1. There are no specifications in each factory, and the methods can be written freely
  2. If the method names of two factories are different, the same set of code is not feasible
  3. Suppose you add an abstract parent class to each factory to unify the production name of each factory

5.1.2 factory transformation method (a bit like abstract factory and a bit like strategic mode)

  1. Add an abstract class TrafficFactory

    public abstract class TrafficFactory {
        abstract Moveable create();
    }
    
  2. CarFactory inherits TrafficFactory

    public class CarFactory extends TrafficFactory{
        public Moveable create(){
            System.out.println("Log operation ===== a car created!! ");
            return new Car();
        }
    }
    
  3. PlaneFactory inherits TrafficFactory

    public class PlaneFactory extends TrafficFactory {
        public Moveable create(){
            System.out.println("Log operation ===== a car created!! ");
            return new Plane();
        }
    }
    
  4. In this way, the method names in the two simple factories are unified, but the two lines of code in the test class are not unified. Continue the transformation

  5. Add a map (magical Map) to TrafficFactory

    public abstract class TrafficFactory {
        static Map<String,TrafficFactory> trafficFactoryMap = new HashMap<>();
        abstract Moveable create();
    }
    
  6. Test class (note that you need to manually initialize the factory into the Map of TrafficFactory. In Spring, you can automatically register by inheriting InitializingBean)

    public class Main {
        static{
            TrafficFactory.trafficFactoryMap.put("PlaneFactory",new PlaneFactory());
            TrafficFactory.trafficFactoryMap.put("CarFactory",new CarFactory());
        }
        public static void main(String[] args) {
            Moveable m = TrafficFactory.trafficFactoryMap.get("PlaneFactory").create();
            m.go();
        }
    }
    

5.2 abstract factory extension

To create a new family, you only need to modify the factory behind new, add classes and methods... (generally speaking, you still have to change the source code)

Like the factory method, if you can flexibly control the new factory, you can realize code reuse (without changing the source code)

6 Summary

  1. Factory methods are a case of abstract methods
  2. Adjectives use interfaces and nouns use abstract classes
  3. Customize any vehicle and inherit Moveable
  4. Define the production process arbitrarily, XXXFactory.create()
  5. Any custom product family (Abstract Factory)
  6. Factory method
    Advantages: the product dimension is easy to expand, disadvantages: it is difficult to expand the family
  7. Abstract factory
    Advantages: the product family number is extended, but the disadvantages are not good. Expand a single product (Spring IOC can solve it)

7 mind map

8 example source code address

https://github.com/ChenJiahao0205/design-pattern/tree/master

last

I learned it through the video of Mr. Ma soldier and the rookie tutorial. Some of the contents may be the same

To read more articles related to design patterns, welcome to my columns [design patterns learning notes] and [design patterns]

After the release of 23 design pattern articles, I will publish a complete mind map, pay attention and don't get lost

Thank you for reading here. If there are any deficiencies in the article, you are welcome to point out; Yanzu point a praise, Yanzu point a praise, Yanzu point a praise, welcome everyone to pay attention to and forward the article!

Posted by jaykappy on Wed, 01 Sep 2021 20:28:50 -0700