[Design pattern] ------ Factory method pattern

Factory method pattern

Mobile phone factories make mobile phones, soap factories make soaps, and pharmaceutical factories make medicines.

Suppose there is a large class of objects A1, A2, A3, A4 ... they all have a common parent class A
A1 can be thought of as a mobile phone, A2 can be thought of as soap ...

(A1Factory in the example below is a mobile phone factory, A2Factory is a soap factory)

So how to use the factory method pattern to create these objects? See an example

1. Define the interface of a factory and the method of returning an entity

interface Factory{
	// 定义一个方法,返回A
	A create();
}

2. For each object, define and create their factory, and each factory implements the factory interface of the first step

class A1Factory implement Factory{
	// A1的工厂类,返回A1对象,用A引用返回出来
	public A creat(){
		return new A1();
	}
}
class A2Factory implement Factory{
	// A2的工厂类,返回A2对象,也用A引用返回出来
	public A creat(){
		return new A2();
	}
}
A3、A4类似

3. When using

Seeing the following effect, you can probably understand what it means. The object is created by the parent class of the factory, and also accessed by the corresponding parent class A. That is equivalent to shielding the difference of subclasses, as long as a factory is changed at the source, then the returned A is the subclass object corresponding to the A generated in the factory.

public A getObj(Factory f){
	return f.create();
}

main(){
	// 给手机工厂,出来就是手机对象
	A A1 = getObj(new A1Factory());
	// 给肥皂工厂,出来就是肥皂对象
	A A2 = getObj(new A2Factory());
}

Pros and cons

Obviously, the factory method pattern, each object needs to be created for him to create a corresponding factory class. This is both an advantage and a disadvantage.
The advantage is because it does this, compared to the simple factory, it delays the instantiation of the class to the subclass factory.
The shortcomings are because of this, every time there is a new type, it is necessary to create a corresponding factory, which feels redundant.

Expand

Often, in each subclass factory of the factory method pattern, the simple factory pattern is used.
In other words, the create method of A1Factory does not necessarily return only A1. It may be a subclass of A1. As for which one, you can add a type parameter to the create method and distinguish it according to the type.

In short, this means that in actual production, in many cases, multiple design patterns are used together, not just a certain design pattern.

Published 203 original articles · praised 186 · 210,000 views

Guess you like

Origin blog.csdn.net/java_zhangshuai/article/details/105170508