Take two examples to quickly understand the simple factory pattern in Java:
Nuwa made people out of soil
There is a saying: "When the world was opened, there were no people, so Nuwa made people out of soil." Nuwa needed to make people out of soil. Humans, but before Nuwa created humans, the concept of humans only existed in Nuwa’s thoughts.
Nuwa creates humans, this is the application of the simple factory model.
First of all, in this idea of creating humans, there are several important roles: Nuwa herself, the abstract concept of human beings, and the specific humans created by Nuwa.
1.) Nuwa is a factory class, which is the core role of the simple factory model.
2.) Each of Gu Xiu’s people, including Zhang San, Li Si, etc. These people are the specific product roles in the simple factory model
3.) Abstract people are an idea that first existed only in Nuwa’s mind. The specific people created by Nuwa according to this idea all conform to the This abstract definition of human being. In other words, this abstract idea stipulates the interfaces (features or functions) that all specific people must have
The UML class diagram is shown below:
Understand the above things, and then understand the following example, Comprehensive understanding, I believe that after reading this article, you will have a good understanding of the Java simple factory model:
There is a farm company that specializes in selling various fruits to the market. In this system, the following fruits need to be described:
Grapes Grape
Strawberry
Apple
fruit is different from other plants and can eventually be picked and eaten, so a natural approach is to build an interface that is applicable to all kinds of fruits in order to distinguish it from other plants on the farm,
At this time, an interface is declared for the fruit class, which is reflected in the code:
public interface Fruit { // 生长 void grow(); // 收获 void harvest(); // 种植 void plant(); }
The fruit interface stipulates the interfaces that all fruits must implement, including the methods plant() and grow() that any fruit class must have. and harvest();
The Apple class is a type of fruit class, so it implements all the methods declared by the fruit interface. In addition, since apples are perennial plants, there is an additional treeAge property to describe the age of the apple tree. The code is as follows:
package fac; public class Apple implements Fruit { // 通过implements实现接口Fruit private int treeAge; public void grow() { log( " Apple is growing " ); } public void harvest() { log( " Apple has been harvested " ); } public void plant() { log( " Apple ha been planted " ); } public static void log(String msg) { System.out.println(msg); } public int getTreeAge() { return treeAge; } public void setTreeAge( int treeAge) { this .treeAge = treeAge; } }
Similarly, Grape:
package fac; public class Grape implements Fruit{ private boolean seedless; public void grow(){ log("Grape is growing."); } public void harvest(){ log("Grape has been harvested"); } public void plant(){ log("Grape ha been planted"); } public static void log(String msg){ System.out.println(msg); } public boolean isSeedless() { return seedless; } public void setSeedless(boolean seedless) { this.seedless = seedless; } }
Strawberry Stuawberry:
package fac; public class Strawberry implements Fruit{ public void grow(){ log("Strawberry is growing"); } public void harvest(){ log("Strawberry has been harvested"); } public void plant(){ log("Strawberry has been planted"); } public static void log(String msg){ System.out.println(msg); } }
The farm gardener is also part of the system, represented by a class, FruitGardener class, the code is as follows:
package fac; public class FruitGardener{ public static Fruit factory(String which)throws Exception{ if(which.equalsIgnoreCase("apple")){ return new Apple(); }else if(which.equalsIgnoreCase("strawberry")){ return new Strawberry(); }else if (which.equalsIgnoreCase("grape")){ return new Grape(); }else{ throw new Exception("Bad fruit request"); } } }
At this time Someone came to the orchard and asked the gardener, "Tell us about your fruits." So the gardener:
package fac; public class People { public static void main(String[] args) throws Exception { FruitGardener fg=new FruitGardener(); Fruit ap=fg.factory("Apple"); ap.grow(); Fruit gp=fg.factory("Grape"); gp.plant(); Fruit dd=fg.factory("ddd");//抛出Bad fruit request异常 } }
(Note: The above code is compiled and passed under JDK5.0, Myeclise3.2)
By analogy with the two examples, the gardener is equivalent to Nuwa, and the fruit is equivalent to a specific person, interface Fruit is equivalent to the abstract concept of people existing in Nuwa's thoughts.
From the above two examples, it can be concluded that the simple factory pattern needs to be composed of the following roles:
Interface
int ] by the following roles Third example:
Pay attention to compare the differences between the following three examples
Example 1:
package org.jzkangta.factorydemo01; //定义接口 interface Car{ public void run(); public void stop(); } //具体实现类 class Benz implements Car{ public void run(){ System.out.println("Benz开始启动了。。。。。"); } public void stop(){ System.out.println("Benz停车了。。。。。"); } } //具体实现类 class Ford implements Car{ public void run(){ System.out.println("Ford开始启动了。。。"); } public void stop(){ System.out.println("Ford停车了。。。。"); } } //工厂 class Factory{ public static Car getCarInstance(){ return new Ford(); } } public class FactoryDemo01 { public static void main(String[] args) { Car c=Factory.getCarInstance(); c.run(); c.stop(); } }
package fac; //定义接口 interface Car{ public void run(); public void stop(); } //具体实现类 class Benz implements Car{ public void run(){ System.out.println("Benz开始启动了。。。。。"); } public void stop(){ System.out.println("Benz停车了。。。。。"); } } class Ford implements Car{ public void run(){ System.out.println("Ford开始启动了。。。"); } public void stop(){ System.out.println("Ford停车了。。。。"); } } //工厂 class Factory{ public static Car getCarInstance(String type){ Car c=null; if("Benz".equals(type)){ c=new Benz(); } if("Ford".equals(type)){ c=new Ford(); } return c; } } public class FactoryDemo02 { public static void main(String[] args) { Car c=Factory.getCarInstance("Benz"); if(c!=null){ c.run(); c.stop(); }else{ System.out.println("造不了这种汽车。。。"); } } }
interface Car{ public void run(); public void stop(); } class Benz implements Car{ public void run(){ System.out.println("Benz开始启动了。。。。。"); } public void stop(){ System.out.println("Benz停车了。。。。。"); } } class Ford implements Car{ public void run(){ System.out.println("Ford开始启动了。。。"); } public void stop(){ System.out.println("Ford停车了。。。。"); } } class Toyota implements Car{ public void run(){ System.out.println("Toyota开始启动了。。。"); } public void stop(){ System.out.println("Toyota停车了。。。。"); } } class Factory{ public static Car getCarInstance(String type){ Car c=null; try { c=(Car)Class.forName("org.jzkangta.factorydemo03."+type).newInstance();//利用反射得到汽车类型 } catch (InstantiationException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IllegalAccessException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (ClassNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } return c; } } public class FactoryDemo03 { public static void main(String[] args) { Car c=Factory.getCarInstance("Toyota"); if(c!=null){ c.run(); c.stop(); }else{ System.out.println("造不了这种汽车。。。"); } } }
Example 1. Although a simple factory is implemented, each We can only get one kind of car at a time. If we want to change to another kind, we have to modify the factory, which is too inconvenient. However, Example 2 changes this situation, so that we can change the car according to our needs, but what we replace is Cars must exist in the implementation class. If we want to add a new car, we still have to change the factory. Through improvement, Example 3 uses the reflection mechanism to get the car type, so that when we need to add a new car , there is no need to modify the factory, but only need to add the class to be implemented. In other words, if you want to add any kind of car, you can just add the car class without changing the factory. Thus achieving the effect of factory separation.
For more articles related to the simple factory pattern in Java, please pay attention to the PHP Chinese website!