Design Patterns Factory Pattern - Abstract Factory pattern


Design Patterns Factory Pattern - Abstract Factory pattern

Abstract factory pattern:

Cluster defines an interface for creating objects related or dependent relationship, without having to explicitly specify a specific class.

Let's look at the use of the abstract factory pattern to achieve the pizza project.

Source: Kaige Java (kaigejava)

Let's look at the structure of the project:

document_image_rId9.png

Description:

1: factory interface

2: two implementation class

3: order object

4: Test class.

Look at the specific code:

IFactoryInterface:

document_image_rId10.png

BeiJinFatory:

document_image_rId11.png

FactoryOrderPizza

document_image_rId12.png

Test categories:

document_image_rId13.png


Three kinds of factory pattern:

1: The instantiate an object placed inside a simple class, then this is a simple factory pattern (also called static factory mode)

2: Method with specific examples of (that is, its subclasses), this is the factory method to create an object if we put the object instantiation code abstract, abstracted into. Meaning the factory method pattern: the creation of objects, from which to create a delay in the class to subclass the inside to create the object.

Reliance on abstract principles:

1: Do not hold a reference variable specific class.

Appreciated: A a = new A (); in this way is held by a variable A particular object. In the factory mode, we can do this: A a = SF ( "A"); or A a = create ( "A"); or A a = new Factory (new CreateA ());

2: Do not let the class inherits from a particular class, inherited from abstract to abstract classes or interfaces.

We need to know if the class A inherits a specific class B. Such a strong dependence is not easy to extend. And we use an interface or an abstract class, then it is convenient expanded.

3: Do not override methods in the base class has been achieved

We design the base class, the method has been implemented in principle is a subclass inherits this base class for all public (common) method. Subclass can be used without the cover. As we have pizza case of pizza baking, cutting and packing method.

document_image_rId14.png

Description:

Benpian by adding the previous two articles, we have completed the factory pattern to explain. But, to be honest, Kaige feel themselves talking about is not very clear. So the next article, Kaige will be three models do comparison, then summarized. I hope to be able to see through the factory model to explain the next article.

Git above the code has been uploaded.

Contact Kaige - "Kaige Java (kaigejava)

Kaige or personal blog: www.kaigejava.com  personal blog can whisper above Kaige Oh!




Guess you like

Origin blog.51cto.com/kaigejava/2433154