The story of Nuwa mending the sky has been heard by all of us. Today, it is not the job of creating a person to tell the story of Nuwa's creator.
The word has been abused by modern people. This story is to say that Nuwa, after mending the sky, went down to the earth to see, wow, the scenery is so beautiful, the sky is Zhanzhan.
Blue, water is clear, air is fresh, too beautiful, and then stay for a long time, a little lonely, no animals, these see
It's all static. What should I do?
Don't forget it's a fairy. There's nothing you can't do. So Nuwa set up the Eight Diagrams Furnace and started to create people.
The specific process is as follows: first, the mud is kneaded, then baked in a gossip oven, and then thrown to the ground to grow, but accidents always occur:
The first clay baker, ZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZ
The second baking clay man, ZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZ
Where is the black man!
The third baking clay man, ZZ~ZZ, baking while watching, hey, just right, Perfect! Good quality, yellow race! [Note: RB people
Not included in this list)
This process is still interesting. First, look at the class diagram:
This process is represented by a program. First of all, we define a general term for human beings.
package com.alex.patterns.factoryMethod;
/**
* @author Alex
* Define a generic term for human beings
*/
public interface Human {
// First of all, define what human beings are.
// People are happy, will laugh, originally intended to use smile to express, think laugh is more appropriate, for a long time did not laugh;
public void laugh();
// Human beings will cry, representing pain.
public void cry();
// Human beings can speak
public void talk();
}
Then define specific races:
package com.alex.patterns.factoryMethod;
/**
* @author Alex
* Yellow race, this translation is inaccurate, will point it
*/
public class YellowHuman implements Human {
public void cry() {
System.out.println("Yellow people cry");
}
public void laugh() {
System.out.println("Yellow people will laugh, happy ah!");
}
public void talk() {
System.out.println("The yellow race can talk, usually in double bytes.");
}
}
White race:
package com.alex.patterns.factoryMethod;
/**
* @author Alex
* White race
*/
public class WhiteHuman implements Human {
public void cry() {
System.out.println("White people cry");
}
public void laugh() {
System.out.println("White people laugh, aggressive laughter");
}
public void talk() {
System.out.println("White people can talk, usually in single byte!");
}
}
Black race:
package com.alex.patterns.factoryMethod;
/**
* @author Alex
* Black race
*/
public class BlackHuman implements Human {
public void cry() {
System.out.println("The Negro will cry.");
}
public void laugh() {
System.out.println("The Negro will laugh.");
}
public void talk() {
System.out.println("Negroes can talk, but ordinary people can't understand.");
}
}
The definition of race is finished, so we define the Eight Diagrams Furnace:
package com.alex.patterns.factoryMethod;
/**
* @author Alex
* Today, the story of Nuwa's creation of human beings is summarized as follows: Long, long ago, Pangu opened up the world and created the sun, moon, stars, mountains, vegetation, heaven and earth a flourishing One.
* day,Nuwa went down once, hey! Too lonely, too lonely, no laughing, crying, talking East.
* Then what shall I do? Don't worry, Nuwa, immortals, make it, then knead the mud and bake it in a gossip stove (which later became the treasure of Taiplatinum Star). Then someone came along:
* We present this producer's process in Java programs:
*/
public class HumanFactory {
// Set an oven, stuff mud in, and people come out. This is too advanced.
@SuppressWarnings("rawtypes")
public static Human createHuman(Class c) {
Human human = null; // Define a type of human
try {
human = (Human) Class.forName(c.getName()).newInstance(); // Produce a race
} catch (InstantiationException e) {// If you don't say the individual color, you can't roast it. You need white and black. You can't roast until you speak.
System.out.println("The color of the race must be specified");
} catch (IllegalAccessException e) { // If there is a problem with the definition of race, it can't be baked. This is __________
System.out.println("Error in ethnicity definition!");
} catch (ClassNotFoundException e) { // Where can I make it for you?!
System.out.println("Son of a bitch, you can't find the race you've designated! _________");
}
return human;
}
}
Then we declare Nuwa:
package com.alex.patterns.factoryMethod;
/**
* @author Alex
* Today, the story of Nuwa's creation of human beings is summarized as follows: Long, long ago, Pangu opened up the world and created the sun, moon, stars, mountains, vegetation, heaven and earth a flourishing One.
* day,Nuwa went down once, hey! Too lonely, too lonely, no laughing, crying, talking East.
* Then what shall I do? Don't worry, Nuwa, immortals, make it, then knead the mud and bake it in a gossip stove (which later became the treasure of Taiplatinum Star). Then someone came along:
* We present this producer's process in Java programs:
*/
public class HumanFactory {
// Set an oven, stuff mud in, and people come out. This is too advanced.
@SuppressWarnings("rawtypes")
public static Human createHuman(Class c) {
Human human = null; // Define a type of human
try {
human = (Human) Class.forName(c.getName()).newInstance(); // Produce a race
} catch (InstantiationException e) {// If you don't say the individual color, you can't roast it. You need white and black. You can't roast until you speak.
System.out.println("The color of the race must be specified");
} catch (IllegalAccessException e) { // If there is a problem with the definition of race, it can't be baked. This is __________
System.out.println("Error in ethnicity definition!");
} catch (ClassNotFoundException e) { // Where can I make it for you?!
System.out.println("Son of a bitch, you can't find the race you've designated! _________");
}
return human;
}
}
In this way, the world will be lively and people will have it, but it is too tired to create this way, and the immortals will be tired, so what should we do? The gods think
Yes: I stuffed in a mud, and a group of people came out at random, whether they were black, white or yellow, as long as they were human. (Look, fairies steal it.)
Lazy, let alone us, first modify the class diagram:
Then look at our program modification, first modify HumanFactory.java, add the createHuman() method:
package com.alex.patterns.factoryMethod;
import java.util.List;
import java.util.Random;
public class HumanFactory1 {
// Set an oven, stuff mud in, and people come out. This is too advanced.
@SuppressWarnings("rawtypes")
public static Human createHuman(Class c) {
Human human = null; // Define a type of human
try {
human = (Human) Class.forName(c.getName()).newInstance(); // Produce a race
} catch (InstantiationException e) {// If you don't say the individual color, you can't roast it. You need white and black. You can't roast until you speak.
System.out.println("The color of the race must be specified");
} catch (IllegalAccessException e) { // If there is a problem with the definition of race, it can't be baked. This is __________
System.out.println("Error in ethnicity definition!");
} catch (ClassNotFoundException e) { // Where can I make it for you?!
System.out.println("Son of a bitch, you can't find the race you've designated! _________");
}
return human;
}
// Nuwa got angry and stuffed a mass of mud into the gossip stove. Whatever kind of person she produced, whatever kind of person she was.
@SuppressWarnings("rawtypes")
public static Human createHuman() {
Human human = null; // Define a type of human
// First of all, how many implementation classes and how many species are obtained?
List<Class> concreteHumanList = ClassUtils.getAllClassByInterface(Human.class); // How many races are defined?
// The Eight Diagrams Furnace started to burn whoever it wanted.
Random random = new Random();
int rand = random.nextInt(concreteHumanList.size());
human = createHuman(concreteHumanList.get(rand));
return human;
}
}
Then see how Nuwa did it:
package com.alex.patterns.factoryMethod;
/**
* @author Alex
* First of all, define Nuwa. It's really a god of the sum.
*/
public class NvWa1 {
public static void main(String[] args) {
// Nuwa's first human creation, experimental nature, fewer manufacturing points, insufficient fire, defective products
System.out.println("------------The first people created were white people.-----------------");
Human whiteHuman = HumanFactory.createHuman(WhiteHuman.class);
whiteHuman.cry();
whiteHuman.laugh();
whiteHuman.talk();
// Nuwa created a man for the second time. She added more fire and then produced a second defective product, the black man.
System.out.println("\n\n------------The second generation of people was created like this: black people.-----------------");
Human blackHuman = HumanFactory.createHuman(BlackHuman.class);
blackHuman.cry();
blackHuman.laugh();
blackHuman.talk();
// The third batch of people, the fire is just mastered, the yellow race (do not write yellow people, so as not to cause ambiguity). Note: RB people do not belong to this list.
System.out.println("\n\n------------The third group of people was created like this: yellow race-----------------");
Human yellowHuman = HumanFactory.createHuman(YellowHuman.class);
yellowHuman.cry();
yellowHuman.laugh();
yellowHuman.talk();
// Nuwa is restless, love is what kind of people is what kind of people, burn it
for (int i = 0; i < 100000000; i++) {
System.out.println("\n\n------------Race is randomly generated.-----------------" + i);
Human human = HumanFactory1.createHuman();
human.cry();
human.laugh();
human.talk();
}
}
}
Wow, the world is busy! But it's not finished yet. You can't run this program. There's something else like this:
package com.alex.patterns.factoryMethod;
import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;
/**
* @author Alex
*
*/
@SuppressWarnings("all")
public class ClassUtils {
// Give an interface and return all implementation classes of that interface
public static List<Class> getAllClassByInterface(Class c) {
List<Class> returnClassList = new ArrayList<Class>(); // Return result
// If it's not an interface, it's not handled
if (c.isInterface()) {
String packageName = c.getPackage().getName(); // Get the current package name
try {
List<Class> allClass = getClasses(packageName); // Get all classes under the current package and subpackage
// Determine whether it's the same interface?
for (int i = 0; i < allClass.size(); i++) {
if (c.isAssignableFrom(allClass.get(i))) { // Is judging an interface?
if (!c.equals(allClass.get(i))) { // Not in itself
returnClassList.add(allClass.get(i));
}
}
}
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
return returnClassList;
}
// Find all classes from a package, but not in a jar package
private static List<Class> getClasses(String packageName) throws ClassNotFoundException, IOException {
ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
String path = packageName.replace('.', '/');
Enumeration<URL> resources = classLoader.getResources(path);
List<File> dirs = new ArrayList<File>();
while (resources.hasMoreElements()) {
URL resource = resources.nextElement();
dirs.add(new File(resource.getFile()));
}
ArrayList<Class> classes = new ArrayList<Class>();
for (File directory : dirs) {
classes.addAll(findClasses(directory, packageName));
}
return classes;
}
private static List<Class> findClasses(File directory, String packageName) throws ClassNotFoundException {
List<Class> classes = new ArrayList<Class>();
if (!directory.exists()) {
return classes;
}
File[] files = directory.listFiles();
for (File file : files) {
if (file.isDirectory()) {
assert !file.getName().contains(".");
classes.addAll(findClasses(file, packageName + "." + file.getName()));
} else if (file.getName().endsWith(".class")) {
classes.add(
Class.forName(packageName + '.' + file.getName().substring(0, file.getName().length() - 6)));
}
}
return classes;
}
}
You know, this ClassUtils is a treasure. It's very useful. You can find all the implementation classes by one interface, or you can.
In order to find all the subclasses by the parent class, we need to modify this by ourselves. Think about it, it's very simple! The complete class diagram is as follows:
Let's conclude, especially with the addition of createHuman(), is this factory more scalable? You see you need to add one more.
Personal race, as long as you continue to integrate the Human interface, and then nothing need to be modified to produce, the specific output, that is to say, gossip furnace.
Come to the conclusion, the simple factory model is so simple, so let's introduce another question: people have sex, men and women, how can you have no area?
Don't, don't worry, this and listen to the next decomposition! __________
Another very important application of the factory method pattern is Lazy initialization. What is delayed initialization?
When an object is initialized, it is not released. When it is used again, it does not need to be initialized again. It can be obtained directly from memory.
How to achieve it is very simple. Look at an example.
package com.alex.patterns.factoryMethod;
import java.util.HashMap;
/**
* @author Alex
*/
@SuppressWarnings("all")
public class HumanFactory2 {
// Define a MAP where all initialized Human objects are placed
//Be careful
private static HashMap<String, Human> humans = new HashMap<String, Human>();
//Be careful
// Set an oven, stuff mud in, and people come out. This is too advanced.
public static Human createHuman(Class c) {
Human human = null; // Define a type of human
try {
// If there is one in the MAP, it is taken out directly without initialization.
//Be careful
if (humans.containsKey(c.getSimpleName())) {
human = humans.get(c.getSimpleName());
} else {
human = (Human) Class.forName(c.getName()).newInstance();
// Put it in the MAP
humans.put(c.getSimpleName(), human);
}
//Be careful
} catch (InstantiationException e) {// If you don't say the individual color, you can't roast it. You need white and black. You can't roast until you speak.
System.out.println(" The color of the race must be specified ");
} catch (IllegalAccessException e) { // Certain definitions of race have problems, then it can't be baked, this is ()()()()()()()()()()()()()()()()()()()()()(
System.out.println(" Error in ethnicity definition! ");
} catch (ClassNotFoundException e) { // Where can I make it for you?! System.out.println("Bastard, you can't find the race you specified! "";
}
return human;
}
}
Simply, add the code that pays attention to the middle part. This is a practical case where class initialization consumes a lot of resources. For example, you need to connect hard.
Components, or to initialize a class, need to prepare more conditions (parameters), which can reduce the complexity of the project.