5. Factory Method Pattern

Recommended article: The most understandable design pattern series analysis: simple factory pattern : https://blog.csdn.net/carson_ho/article/details/52343584   


The following is a basic factory method pattern

 Everyone has heard of the story of Nuwa mending the sky. I won't talk about it today. Talking about the story of Nuwa's creation of man is not the work of "creating man". This term has been abused by modern people. The story is that Nuwa, after mending the sky, went down to the mortal world to see, wow, the scenery is so beautiful, the sky is blue, the water is clear, the air is fresh, it is so beautiful, but it takes a long time to stay. It's a bit lonely, there are no animals, all these things are static, what should I do?

    Don't forget that she is an immortal, there is nothing she can't do, so Nuwa set up a gossip furnace (technical term: building a factory) and started to create people. Baked, then thrown on the ground to grow, but accidents always happen:

    The first time I baked a clay figurine, zizizizi~~, I felt that I should accept it, and I threw it on the ground, biubiu, a white man was born, without any help!

    The second time I baked a clay figurine, zizizizi~~, I didn't bake it last time, I will bake it a little longer this time, and throw it on the ground, hey, it's overcooked, black person!

    The third time to bake a clay figurine, zizizizi~~, watching while baking, hey, just right, Perfect! Youpin, yellow race!

   

 Do it in code:

content:



Human.java

package No5_FactoryMethodPattern;

/**
 * Define a person's interface. As a person, the following three actions are required
 */
public interface Human {
    public void laugh();

    public void cry();

    public void talk();
}

YellowHuman.java

package No5_FactoryMethodPattern;

/**
 * Define a specific race
 * yellow race
 */
public class YellowHuman implements Human {
    @Override
    public void laugh() {
        System.out.println("Yellow people will laugh");
    }

    @Override
    public void cry() {
        System.out.println("Yellow people cry");
    }

    @Override
    public void talk() {
        System.out.println("Yellow race people can speak, generally speaking are double bytes");
    }
}

WhiteHuman.java

package No5_FactoryMethodPattern;

/**
 * Defined to a specific race
 * white race
 */
public class WhiteHuman implements Human {
    @Override
    public void laugh() {
        System.out.println("White people laugh");
    }

    @Override
    public void cry() {
        System.out.println("White people cry");
    }

    @Override
    public void talk() {
        System.out.println("Caucasians can speak, usually single-byte");
    }
}

BlackHuman.java

package No5_FactoryMethodPattern;

/**
 * Defined to a specific race
 * black people
 */
public class BlackHuman implements Human {
    @Override
    public void laugh() {
        System.out.println("Black people laugh");
    }

    @Override
    public void cry() {
        System.out.println("Black people cry");
    }

    @Override
    public void talk() {
        System.out.println("Black people can talk");
    }
}

HumanFactory.java

package No5_FactoryMethodPattern;

/**
 * Today I will tell you the story of Nuwa creating a human being. The outline of the story is as follows:
 * A long, long time ago, Pangu opened up the world, using his body to create the sun, moon, stars, mountains and rivers, and the world was prosperous.
 * One day, Nuwa walked into the lower world, hey, too lonely, too lonely, there is no one who can laugh, cry, or talk
 * then what should we do? Don't worry, Nuwa, the goddess, make it, then squeeze the mud and put it on the gossip furnace (later this became the treasure of Taibaijinxing)
 * Medium roast, so there are people:
 * We express this process of producing people with a java program:
 */
public class HumanFactory {
//Define an oven, put mud in, and people come out
    public static Human createHuman(Class c){
        Human human = null;
        try{
            human = (Human)Class.forName(c.getName()).newInstance();//Generate a human race
        }catch(InstantiationException e){
            System.out.println("The color of the race must be specified");
        }catch(ClassNotFoundException e){
            System.out.println("Bastard, the race you specified can't be found!");
        } catch (IllegalAccessException e) {
            System.out.println("Race definition error");
        }

        return human;
    }

}

NvWa.java

package No5_FactoryMethodPattern;

/**
 * This is Nuwa
 */
public class NvWa {
    public static void main(String[] args) {
        System.out.println("-----The first batch of people created is like this: white people-----");
        Human whiteHuman = HumanFactory.createHuman(WhiteHuman.class);
        whiteHuman.cry();
        whiteHuman.laugh();
        whiteHuman.talk();

        System.out.println("-----The second batch of people created is like this: black people-----");
        Human blackHuman = HumanFactory.createHuman(BlackHuman.class);
        blackHuman.cry();
        blackHuman.laugh();
        blackHuman.talk();

        System.out.println("-----The third batch of people created is like this: yellow race-----");
        Human yellowHuman = HumanFactory.createHuman(YellowHuman.class);
        yellowHuman.cry();
        yellowHuman.laugh();
        yellowHuman.talk();

    }
}

The interpretation of the code is written in the comments, read the code carefully and look down


Definition (Baidu Encyclopedia):

The factory method pattern (FACTORY METHOD) is a commonly used object creation design pattern. The core spirit of this pattern is to encapsulate the invariable part of the class, extract the fickle part of it as an independent class, and achieve solution through dependency injection. The purpose of coupling, reusing and facilitating later maintenance and expansion. Its core structure has four roles, namely abstract factory; concrete factory; abstract product; concrete product.


Factory methods are often used in the following two situations:

The first situation is that for a product, the caller clearly knows which specific factory service should be used, instantiate the specific factory, and produce a specific product.
In the second case, you just need a product, and you don’t want to know or need to know which factory is producing it, that is, the final decision on which specific factory to choose is on the producer side, and they instantiate a product according to the current system conditions. The specific factory is returned to the user, and this decision-making process is transparent to the user.


Code examples are taken from "24 Design Patterns and 6 Design Principles"



Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324593555&siteId=291194637