Understand the factory model

3. Factory series

  • First of all, any method or class that can generate an object can be called a factory (as long as a method returns a new object, it can be said to be a factory). Therefore, a singleton is also a factory (static factory)
  • Why is there a factory when there is new?
    1. Flexible control of production process
    2. Permission, decoration, log

Three steps

  1. Customized transportation
  2. Arbitrarily define the production process (in fact, enrich the content of new and do more before new)
  3. Arbitrarily defined product family

introduction

First of all, we go to work today and have to drive out

public class Main {
    public static void main(String[] args) {
        Car c = new Car();
        c.go();
    }
}
package com.hejiale.factorymethod;

public class Car {

    public void go() {
        System.out.println("Car go....");
    }
}

Then, the next day, I wanted to fly out again

public class Main {
    public static void main(String[] args) {
        // Car c = new Car();
        // c.go();
        Plane p = new Plane();
        p.go();
    }
}
package com.hejiale.factorymethod;
public class Plane {
    public void go() {
        System.out.println("Plane fly......");
    }
}

Now, I want to ride a broom out again

package com.hejiale.factorymethod;
public class Main {
    public static void main(String[] args) {
//        Car c = new Car();
//        c.go();
//        Plane p = new Plane();
//        p.go();
        Moveable m=new Broom();
        m.go();
    }

package com.hejiale.factorymethod;
public class Broom {
    public void go(){
        System.out.println("Broom fly....");
    }
}

We can find that every time I change the vehicle, I have to modify all the code. Is there a way to reduce the amount of code modification? The method is to make a parent class or an interface. Let car, plane and broom implement this interface, and then just modify the implementation class of new every time

package com.hejiale.factorymethod;
public interface Moveable {
    void go();
}
package com.hejiale.factorymethod;
public class Car implements Moveable{
    public void go() {
        System.out.println("Car go....");
    }
}
//Main. Just write it in main
Moveable m=new Broom();
m.go();

Using polymorphism, we can easily switch vehicles, that is, now we can customize vehicles at will
Now let's start to solve the second part - arbitrary customized production process. In fact, the "production process" we most often remove is to use the new keyword. Is there any other way? Actually, there are
For example, when we new a vehicle, I also ask you to control the authority (ordinary people, you can take a plane, and you can give it to the captain with higher authority). It's natural to think that after we come out of new, we can write some code, but this will bring a problem, that is, our main method will become complex, Moreover, the permissions of each vehicle are different, so it's a headache for us to set different permissions
So we propose a method. We specially write a class and hand over the details of creating objects and permission control to this class. In this way, on the one hand, the code will become concise. On the other hand, we can also hide the complex permission control from users. Next, we will involve the content of simple factories

3.1 simple factory

package com.hejiale.factorymethod;
public class SimpleVehicleFactory {
    public Car createCar(){
        //Permission operations and log operations can be performed here
        //before processing
        return new Car();
    }
    public Broom createBroom(){
        //before processing
        return new Broom();
    }
    public Plane createPlane(){
        //before processing
        return new Plane();
    }
}

However, the scalability of simple factories is not good
For example, if we want to add a vehicle, we need to modify the simple factory class, which violates the opening and closing principle

3.2 factory method

Therefore, we further modify the code. We can create a factory class for each vehicle. This factory class specifically produces an object

package com.hejiale.factorymethod;
public class CarFactory {
    public Moveable create(){
        //before processing
        System.out.println("a car created");
        return new Car();
    }
}
//Main.main
Moveable m = new CarFactory().create();
m.go();

So now, we can customize the production process at will
Preliminary summary

Customized transportation
    realization Moveable
 Any customized production process
    XXXFactory.create()

3.3 Abstract Factory

Next, we propose a new scene where eggplant (csgo anchor) shoots ak47 while driving and eats bread

package com.hejiale.abstractfactory;
public class Main {
    public static void main(String[] args) {
        Car c = new Car();
        c.go();
        AK47 a = new AK47();
        a.shoot();
        Bread bread = new Bread();
        bread.printName();
    }
}
package com.hejiale.abstractfactory;

public class AK47 {
    public void shoot(){
        System.out.println("what the fuck!What a shot");
    }
}
package com.hejiale.abstractfactory;

public class Bread {
    public void printName(){
        System.out.println("Needle does not poke");
    }
}

So at this time, there is another person, Harry Potter, riding a broom, using a magic wand, eating Oreo mushrooms
Then we can define broom, mushroom and magicstick in the same way
Here, we find a rule that the above two cases constitute a product family, which means that both cases are composed of three parts

  1. vehicle
  2. arms
  3. food
    Here we have to think about a question. Can there be a simple way to quickly switch product families? For example, now there is a western free speech person who drives a tank, uses rumor weapons and uses dollars to corrupt and ignorant people. Do we still need to write a piece of code in main? This is obviously very inconvenient
    Therefore, the abstract factory is officially introduced
    First of all, to be clear, the abstract factory has four roles
  4. Abstract factory
  5. Abstract product
  6. Specific factory
  7. Specific products
    [the external chain picture transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the picture and upload it directly (img-4OqnKQTb-1621386123347)(C:\Users\Documents \ learning notes \ 26 design mode \ md_img.png)]
    So we write out the corresponding classes according to the class diagram

1. Abstract Factory

package com.hejiale.abstractfactory;

/**
 * The abstract factory is responsible for defining the skeleton
 */
public abstract class AbstractFactory {
    abstract Food createFood();
    abstract Weapon createWeapon();
    abstract Vehicle createVehicle();

}

Abstract product

package com.hejiale.abstractfactory;

public abstract class Vehicle {
    abstract void go();
}
package com.hejiale.abstractfactory;

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

package com.hejiale.abstractfactory;

public abstract class Food {
    abstract void eat();
}

Specific factory

package com.hejiale.abstractfactory;

public class ModernFactory extends AbstractFactory{
    @Override
    Food createFood() {
        return new Bread();
    }

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

    @Override
    Vehicle createVehicle() {
        return new Car();
    }
}

Specific products

package com.hejiale.abstractfactory;

public class AK47 extends Weapon{
    public void shoot(){
        System.out.println("what the fuck!What a shot");
    }
}
package com.hejiale.abstractfactory;

public class Bread extends Food{
    public void eat(){
        System.out.println("Needle does not poke");
    }
}
package com.hejiale.abstractfactory;

import com.hejiale.factorymethod.Moveable;

public class Car extends Vehicle{

    public void go() {
        System.out.println("Car go....");
    }
}

Comparison between abstract factory and factory method

In fact, factory method and abstract factory prefer two different dimensions. In factory method, we can easily add products, because we only need to add factory classes. In abstract factory, we can easily define product family, but the problem is that if we add products in product family, it will be more difficult
Therefore, is there a better way to integrate the advantages of the two? The answer is the bean factory brought by spring

Unfinished to be continued

Keywords: Algorithm

Added by Tindo on Fri, 11 Feb 2022 10:37:50 +0200