[Java usage] Java design pattern (two) factory pattern (Factory Pattern)

Contents of this article

1. The definition of factory model

Second, the classification of the factory model

Third, why use the factory model

Fourth, the code implementation of the factory pattern

Five, the source code of the factory model


1. The definition of factory model

Let's first look at the definition of GOF as the factory model:

"Define an interface for creating an object, but let subclasses decide which class to instantiate. Factory Method lets a class defer instantiation to subclasses." (Define an interface for creating an object in the base class, and let the subclass decide which class to instantiate. The factory method delays the instantiation of a class to subclasses.)

Second, the classification of the factory model

(1) Simple Factory (Simple Factory) mode , also known as Static Factory Method Pattern.

(2) Factory Method mode , also known as Polymorphic Factory mode or Virtual Constructor mode;

(3) Abstract Factory (Abstract Factory) mode , also known as Toolkit (Kit or Toolkit) mode.

Third, why use the factory model

(1) Decoupling : Separate the process of object creation and use

(2) Reduce code duplication : If the process of creating an object is very complicated and requires a certain amount of code, and it is used in many places, there will be a lot of duplication of code.

(3) Reduce maintenance costs : Since the creation process is uniformly managed by the factory, business logic changes occur. There is no need to find all the places where an object needs to be created to modify one by one. It only needs to be modified in the factory to reduce maintenance costs.

Fourth, the code implementation of the factory pattern

The code implementation examples of all design patterns can be viewed on Code Cloud, and those who are interested can check it. Code Cloud address: https://gitee.com/no8g/java-design-patterns

The following stories are quoted from the introduction of 24 design patterns and 6 design principles e-books:

Everyone has heard of the story of Nuwa patching the sky. I don’t want to talk about it today. The story of Nuwa’s creation of human beings is not a job of "creating human beings." This term is abused by modern people. This story is told in the Goddess make up the days, down to a mortal look, Wow, the scenery is too beautiful, the sky is the Cham
blue, the water is clear, the air is fresh, too beautiful, and then wait time When I grow up, I feel a little lonely. There are no animals. All these things are static. What should I do?

Don’t forget that it’s a god, there is nothing that can’t be done, so Nuwa set up a gossip stove (technical term: building a factory) and started to create people. The specific process is like this: first squeeze the mud, and then bake it in the gossip stove. , And then thrown on the ground to grow, but accidents will always occur:

It’s the first time to bake a clay figurine. I feel like it should be cooked. Throw it on the ground, biu~, a white man is born, but it’s not cooked!

Baking clay figurines for the second time, Zizizizizizizi~~, it was not cooked last time, this time I will bake it for a while and throw it on the ground, hey, it's over cooked, black man!

Baking clay figurines for the third time, here~z~z~, watching while baking, hey, just right, Perfect! Excellent product, yellow race! [Note: RB people are not included in this list]

Then we use the program to express this process, first define a general term for human beings:

/**
 * Created by IntelliJ IDEA.
 *
 * @Author: hjm
 * @Date: 2021/1/26 21:35
 * Stay hungry,stay foolish!
 * 定义一个人类的统称
 */
public interface Human {

    /**
     * 人是愉快的,会笑的,本来是想用smile表示,想了一下laugh更合适,好长时间没有大笑了
     */
    void laugh();

    /**
     * 人类还会哭,代表痛苦
     */
    void cry();

    /**
     * 人类会说话
     */
    void talk();
}

Then define the specific race:

/**
 * Created by IntelliJ IDEA.
 *
 * @Author: hjm
 * @Date: 2021/1/26 21:41
 * Stay hungry,stay foolish!
 * 白色人种
 */
public class WhiteHuman implements Human {
    @Override
    public void laugh() {
        System.out.println("白色人种会大笑,侵略的笑声");
    }

    @Override
    public void cry() {
        System.out.println("白色人种会哭");
    }

    @Override
    public void talk() {
        System.out.println("白色人种会说话,一般都是但是单字节!");
    }
}
/**
 * Created by IntelliJ IDEA.
 *
 * @Author: hjm
 * @Date: 2021/1/26 21:42
 * Stay hungry,stay foolish!
 * 黑色人种,记得中学学英语,老师说black man是侮辱人的意思,不懂,没跟老外说话
 */
public class BlackHuman implements Human {
    @Override
    public void laugh() {
        System.out.println("黑人会笑");
    }

    @Override
    public void cry() {
        System.out.println("黑人会哭");
    }

    @Override
    public void talk() {
        System.out.println("黑人可以说话,一般人听不懂");
    }
}
/**
 * Created by IntelliJ IDEA.
 *
 * @Author: hjm
 * @Date: 2021/1/26 21:37
 * Stay hungry,stay foolish!
 * 黄色人种,这个翻译的不准确,将就点吧
 */
public class YellowHuman implements Human {
    @Override
    public void laugh() {
        System.out.println("黄色人种会大笑,幸福呀!");
    }

    @Override
    public void cry() {
        System.out.println("黄色人种会哭");
    }

    @Override
    public void talk() {
        System.out.println("黄色人种会说话,一般说的都是双字节");
    }
}

Race is also defined, then we define the Bagua furnace:

/**
 * Created by IntelliJ IDEA.
 *
 * @Author: hjm
 * @Date: 2021/1/26 21:46
 * Stay hungry,stay foolish!
 * 今天讲女娲造人的故事,这个故事梗概是这样的:
 * 很久很久以前,盘古开辟了天地,用身躯造出日月星辰、山川草木,天地一片繁华
 * One day,女娲下界走了一遭,哎!太寂寞,太孤独了,没个会笑的、会哭的、会说话的东东
 * 那怎么办呢?不用愁,女娲,神仙呀,造出来呀,然后捏泥巴,放八卦炉(后来这个成了太白金星的宝贝)中烤,于是就有了人:
 * 我们把这个生产人的过程用Java程序表现出来:
 */
public class HumanFactory {

    /**
     * 定一个烤箱,泥巴塞进去,人就出来,这个太先进了
     */
    public static Human createHuman(Class c) {

        // 定义一个类型的人类
        Human human = null;

        try {
            // 产生一个人种
            human = (Human) Class.forName(c.getName()).newInstance();
        } catch (InstantiationException e) {
            // 你要是不说个人种颜色的话,没法烤,要白的黑的,你说话了才好烤
            System.out.println("必须指定人种的颜色");
        } catch (IllegalAccessException e) {
            // 定义的人种有问题,那就烤不出来了,这是...
            System.out.println("人种定义错误!");
        } catch (ClassNotFoundException e) {
            // 你随便说个人种,我到哪里给你制造去?!
            System.out.println("HD,你指定的人种找不到!");
        }

        return human;
    }
}

Then we declare Nuwa:

/**
 * Created by IntelliJ IDEA.
 *
 * @Author: hjm
 * @Date: 2021/1/26 21:51
 * Stay hungry,stay foolish!
 * 首先定义女娲,这真是额的神呀
 */
public class NvWa {

    public static void main(String[] args) {
        // 女娲第一次造人,试验性质,少造点,火候不足,缺陷产品
        System.out.println("------------造出的第一批人是这样的:白人-----------------");
        Human whiteHuman = HumanFactory.createHuman(WhiteHuman.class);
        whiteHuman.cry();
        whiteHuman.laugh();
        whiteHuman.talk();

        // 女娲第二次造人,火候加足点,然后又出了个次品,黑人
        System.out.println("------------造出的第二批人是这样的:黑人-----------------");
        Human blackHuman = HumanFactory.createHuman(BlackHuman.class);
        blackHuman.cry();
        blackHuman.laugh();
        blackHuman.talk();

        // 第三批人了,这次火候掌握的正好,黄色人种(不写黄人,免得引起歧义),备注:RB人不属于此列
        System.out.println("------------造出的第三批人是这样的:黄色人种-----------------");
        Human yellowHuman = HumanFactory.createHuman(YellowHuman.class);
        yellowHuman.cry();
        yellowHuman.laugh();
        yellowHuman.talk();
    }
}

Five, the source code of the factory model

 

 

 

 end!

Guess you like

Origin blog.csdn.net/weixin_44299027/article/details/113196090