Home >Java >javaTutorial >Simple example of JAVA factory pattern
Now we give a simple use case to simulate a ham production factory. The factory can produce several types of Ham. After creating a factory instance, you only need to tell it what kind of Ham you want to produce, and it will give you You produce:
package test;
interface Ham { //Define the interface to assist in implementing the factory mode
void show();//Various Hams produced by the Ham factory will have the ability to show()
}
public class FatoryModule {//Factory class, used to produce many different types of Ham
public Ham getHam(String HamType) throws Exception{//The action of the factory class object to produce Ham
if (HamType.equals("HamA") ) {
return new HamA(); Type.equals("HamC")) {
return new HamC(); ] args) {//Test code
using using using using use using using through using ‐ ‐ ‐ ` ‐ ‐ args) { The modification amount reaches the minimum
myHam.show(); A product produced by HamA
public void show() {
System.out.println("You got a HamA.");
}
}
class HamB implements Ham { //Another product produced by the factory HamB V Public void show () {
system.out.println ("you get a hamb."); {
System.out.println("You got a HamC.");
For more simple examples of JAVA factory pattern, please pay attention to the PHP Chinese website for related articles!