Design Patterns (2) — Abstract Factory patterns

An overview,

Official explanation: Define an interface for creating an object,but let subclass decide which class to instantiate.Factory Method lets a Class defer defer instantiation to subclass. (Define an interface for creating objects and let subclasses decide which class to instantiate. Factory methods are the instantiation of a class deferred to its subclasses. Factory mode, in which a method (factory method) of a class (factory class) determines the runtime type based on the parameter, creates a new object and returns (factory method).

Participants: product class (AbstractProduct class, ConcreteProduct class), ConcreteFactory class ConcreteFactory

Class diagram:

 

FruitFactory

FruitFactory class diagram:

 

Code diagram:



interface Fruit{
	void display(a);
}
class Apple implements Fruit{

	@Override
	public void display(a) {
		// TODO Auto-generated method stub
		System.out.println("This is an Apple"); }}class Orange implements Fruit{

	@Override
	public void display(a) {
		System.out.println("This is an orange"); }}class Banana implements Fruit{

	@Override
	public void display(a) {
		// TODO Auto-generated method stub
		System.out.println("This is a banana"); }}class FruitFactory {
	public Fruit produce_Fruit(String type){
		// The essence of the factory model is that the factory method of the factory class creates different factory products according to the parameters, which uses polymorphism
		if (type.equalsIgnoreCase("apple")) {
			return new Apple();
		}
		if (type.equalsIgnoreCase("orange")) {
			return new Orange();
		}
		if (type.equalsIgnoreCase("banana")) {
			return new Banana();
		}
		return null; }}public class TestFactory {

	public static void main(String[] args) {
		FruitFactory factory=new FruitFactory();
		factory.produce_Fruit("apple").display();
		factory.produce_Fruit("orange").display();
		factory.produce_Fruit("banana").display(); }}Copy the code

Output result:

This is an Apple
This is an orange
This is a banana
Copy the code

 

Third, summary

The essence of the factory pattern is that the factory method of the factory class creates different factory products based on parameters using an upward transformation, rather than creating each class separately

 

Design Patterns (2) — Abstract Factory patterns