package factory;
public class Test {
public static void main(String[] args) {
Action action=MyFactory.newInstence();
action.run();
}
}
package factory;
import java.util.Scanner;
public class MyFactory {
private MyFactory (){
super();
}
public static Action newInstence(){
System.out.println("输入一个数:");
int num=new Scanner(System.in).nextInt();
if (num==1) {
return new Dog();
}else {
return new Cat();
}
}
}
package factory;
public interface Action {
void run();
}
package factory;
public class Cat implements Action{
@Override
public void run() {
System.out.println("cat run");
}
}
package factory;
public class Dog implements Action{
@Override
public void run() {
System.out.println("dog run");
}
}
As in the above program, cats and dogs have the same behavior, then write an interface to execute a run action, and use this interface as the return value type of the factory (the reference of the parent class points to the object of the subclass, and the method called from Ei is polymorphic Upward transformation in , easy to understand), this method is a static method, you can directly call this method with the factory name (MyFactory), and create a selected subclass object at the same time, and then call it directly through the main function, directly using Action (interface) Generate a subclass object, and then execute the subclass method. The factory pattern is used in complex and common classes, naming some common behaviors as interfaces, and then creating instances through the factory to facilitate file modification