Briefly talk about the factory model

Factory mode: Simply put, there is an internal method called by an interface that can generate an interface subclass object, and has a return value. The return value type is a subclass object of the interface. Privatize the construction z method (no parameters) in the factory, then directly make the method inside the factory public static, and then other classes can directly generate a required subclass object by calling the static method of the factory.
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

Guess you like

Origin blog.csdn.net/u013377003/article/details/51398031