[Original · tutorial · serialization] "design mode of Android"-design mode Creation Mode Chapter 2: Factory method mode

Source: Internet
Author: User
<Big talk design model> description and copyright notice of this tutorial

L this document references and uses free images and content on the Internet, and is released in a free and open manner, hoping to contribute to the mobile Internet and the smart phone age! This document can be reproduced at will, but cannot be used for profit.

L if you have any questions or suggestions about this document, go to the official blog

Http://www.cnblogs.com/guoshiandroid/ (with the following contact information), we will carefully refer to your suggestions and modify this document as needed to benefit more developers!

L The latest and complete content of "big talk design mode" will be regularly updated on the official blog of guoshi studio. Please visit the blog of guoshi studio.

Http://www.cnblogs.com/guoshiandroid/get more updates.

Guoshi studio is a technical team dedicated to enterprise-level application development on the Android platform. It is committed to providing the best Android enterprise-level application development and training services in China.

Official contact information for Enterprise Training and Development Cooperation:

Tel: 18610086859

Email: hiheartfirst@gmail.com

QQ: 1740415547

QQ: 148325348

Guoshi studio is better for you!

 

 View other parts: Overall description and Chapter index of this tutorial

PDF download link

Make McDonald's hamburger fit different tastes of different mm

Example of factory method mode Application Scenario: 

"Do you know the university rules ?", MM asked with dissatisfaction. "What are the rules? Of course I don't know .", Gg said silly, it is obvious that this mm is somewhat dissatisfied with GG's ignorance and inactive. "In college, when two people are determined to be in a relationship, they all need to invite their girlfriends to dinner in the same dormitory," Mm said with a bit of dissatisfaction and coquetry. "Ah? I don't know. I can't ask for a meal for all the beautiful girls. When can I have time? I'm sure it's time and place. I'll be on call !" GG was excited and readily agreed. MM looked up with a smile and looked at this silly GG. "Well, let me think about it. We... We have time next Saturday afternoon. Or, you can take us to McDonald's. "" It's a thing to say. "Then we'll meet you at the McDonald's branch on the south of the central commercial street at five o'clock P.M. next Saturday, I heard that the taste over there is good:-o "," okay, as long as you are happy. "GG replied," No worries!" MM leaves with a smile.

When GG and mm met each other by chance a few days ago, GG once again experienced an unspeakable happiness and excitement. On that day, GG saw mm, and the whole earth was shaking, her sweet and soft voice, her classical hair, her superb body, her proper dress, her elegant and quiet manners, and her music-like manners he was completely fascinated, it seems that there is only one person in the world, as if everything was born for her. Suddenly, the eyes of the two were staggered, and they met each other... Love at first sight! Gg thought, it would be nice to go to McDonald's. I won't cook anyway. Besides, even if I do, I can't do it. It's difficult to make a public speech. What's more, it's a group of beautiful women, go to McDonald's and ask them to pick their own items. ^_^ but I am afraid that my living expenses will be ruined this month. No wonder other people say that the highest consumption in college is spent on my girlfriend ~~~~ (>_< )~~~~

Finally, it was Saturday afternoon. GG, who was overwhelmed by feelings, suddenly became no longer so stupid. This time he booked a seat in advance, which can accommodate 8 people. In addition, the location of the MM seat is detailed, so that everyone knows that the location is better, avoiding the embarrassment of having no location at that time. Gg rushed to McDonald's road, but worried a little. After all, she had to face six beautiful women, and she had just known each other for a few days. "Dear, where is it now ?" MM sent a text message on the mobile phone. gg looked at the time. Oh, my God, it's just a few minutes and five minutes later. It would be too bad if she was late for the first time, so I immediately replied, "Baby, I am here! ", Because McDonald's is on the opposite side, you can see it when you look up. Gg ran to the dining place on the second floor of McDonald's. When she saw all the beautiful women, she was nervous and did not say anything. "This is my boyfriend," said mm, dragging Gg's arm. "Hello, everyone, hello everyone, "Gg said nervously. Busy, I added: "Let's order first. You can do it yourself." "I want to eat chicken wings." "I want a wheat-flavored fish package ", I want a "slice chicken leg package", I want a "milkshake", I want "fries", "I want a hamburger", and "I want a hamburger ", "I want a hamburger with both of them at a Glance." It's speechless. gg certainly cannot know everyone's taste. In desperation, he had to bring these three beautiful women to the service desk and say, in addition to the order items, three hamburgers are required, so what is the taste of the hamburger, the three beautiful women can directly communicate with the waiter.

Description of the factory method mode: 

The factory method pattern also belongs to the class creation mode, also known as the polymorphic ). The factory method mode defines a factory interface for creating product objects and delays the actual creation to the subclass. The core factory category is no longer responsible for product creation. In this way, the core class becomes an abstract factory role and is only responsible for the interfaces that must be implemented by specific factory subclass, the advantage of further abstraction is that the factory method mode enables the system to introduce new products without modifying the specific factory role.

Definition: Define an interface for creating an object, but let subclassesdecide which class to instantiate. Factory method lets a class deferinstantiation to subclasses.

Factory method modeUMLFigure: 

The roles in the factory method model and their responsibilities are as follows:

Abstract Factory role: the Core of the factory method mode, which must be implemented by any factory class.

Concrete Creator: A factory class is an implementation of an abstract factory and is responsible for instantiating product objects.

Abstract Product role: the parent class of all objects created in simple factory mode. Note that the parent class can be an interface or an abstract class, it describes the common public interfaces of all instances.

Concrete Product role: a specific instance object created by a simple factory. These products often share a common parent class.

In-depth analysis of factory method and Mode:

In simple factory mode, a class is used to create all products. Although the service end and the service end are separated from each other, the service end does not need to care about the specific creation process of the product, the only thing the client needs to do is to call the static method of a simple factory to obtain the desired product. However, the simple factory mode violates the "open and closed principle" in a strict sense, which makes it necessary to modify the source code of the factory class once a new product is added, in this way, the creation logic of the new product is added to the simple factory for the client to call. The factory method mode is further abstracted based on the simple factory mode. Because the core of the factory method mode is the abstract factory role and the object-oriented polymorphism is used, the factory method mode maintains the advantages of the simple factory mode, overcome the disadvantages of the simple factory model violating the "open and closed principle.

In the factory method mode, the core factory category no longer provides the creation of all products, but rather assigns the specific product creation work to the subclass. What is the core factory at this time? Standard! The core factory class only needs to be responsible for formulating the interface that the specific factory needs to implement. The specific work is left to the subclass to create.

In actual use, there are usually multi-level product structures between idle products and specific products, as shown in:

Factory method mode use scenario analysis and code implementation: 

Different beauties eat hamburgers at the same time, but different beauties have different tastes. This is what GG does not know, and it is not necessary to know, if you know it, your girlfriend will be unhappy ~~~~ (>_< )~~~~ . At this time, GG only needs to take these beautiful women to the service desk, so that these beautiful women can directly talk to the service staff about what they need and the hamburger will be OK. However, no matter what Hamburger these sisters need, the result must be a hamburger.

The UML Model diagram is as follows:

The specific implementation code is as follows:

Create a new interface for food:

PackageCom. diermeng. designpattern. fatorymethod;

/*

* Abstract interface of food

*/

Public InterfaceFood {

/*

* Get the corresponding food

*/

Public VoidGet ();

}

Create a food factory interface:

Package com. diermeng. designpattern. fatorymethod;

/*

* Abstract interfaces of food production plants

*/

Public interface foodfactory {

/*

* The production factory produces the corresponding food

*/

Public Food getfood ();

}

Next we will build a specific product: beef burger and chicken burger.

PackageCom. diermeng. designpattern. fatorymethod. impl;

ImportCom. diermeng. designpattern. fatorymethod. Food;

 

/*

* Beef burger

*/

Public ClassBeefburgerImplementsFood {

/*

* Get A beef burger

*/

Public VoidGet (){

System.Out. Println ("Get a beef burger ");

}

}

PackageCom. diermeng. designpattern. fatorymethod. impl;

ImportCom. diermeng. designpattern. fatorymethod. Food;

 

/*

* Chicken burger

*/

Public ClassChickenburgerImplementsFood {

/*

* Get a chicken burger

*/

Public VoidGet (){

System.Out. Println ("get a chicken burger ");

}

}

Create a beef burger Factory:

PackageCom. diermeng. designpattern. fatorymethod. impl;

ImportCom. diermeng. designpattern. fatorymethod. Food;

ImportCom. diermeng. designpattern. fatorymethod. foodfactory;

 

/*

* Beef burger Factory

*/

Public ClassBeefburgerfactoryImplementsFoodfactory {

/*

* Produce a beef hamburger

* @ See COM. diermeng. designpattern. fatorymethod. foodfactory # getfood ()

*/

PublicFood getfood (){

Return NewBeefburger ();

}

 

}

 

Create a chicken hamburger factory:

PackageCom. diermeng. designpattern. fatorymethod. impl;

ImportCom. diermeng. designpattern. fatorymethod. Food;

ImportCom. diermeng. designpattern. fatorymethod. foodfactory;

 

/*

* Muscle hamburger factory

*/

Public ClassChickenburgerfactoryImplementsFoodfactory {

/*

* Produce a muscle hamburger

* @ See COM. diermeng. designpattern. fatorymethod. foodfactory # getfood ()

*/

Public Food getfood (){

Return new chickenburger ();

}

 

}

Finally, we create a test client:

PackageCom. diermeng. designpattern. fatorymethod. client;

ImportCom. diermeng. designpattern. fatorymethod. Food;

ImportCom. diermeng. designpattern. fatorymethod. foodfactory;

ImportCom. diermeng. designpattern. fatorymethod. impl. beefburgerfactory;

ImportCom. diermeng. designpattern. fatorymethod. impl. chickenburgerfactory;

 

 

/*

* Test the client

*/

Public ClassFactorymethodtest {

Public Static VoidMain (string [] ARGs ){

// Obtain chickenburgerfactory

Foodfactory chickenburgerfactory =NewChickenburgerfactory ();

 

// Use chickenburgerfactory to obtain the chickenburger Instance Object

Food chickenburger = chickenburgerfactory. getfood ();

Chickenburger. Get ();

 

 

// Obtain beefburgerfactory

Foodfactory beefburgerfactory =NewBeefburgerfactory ();

 

// Use beefburgerfactory to obtain the beefburger Instance Object

Food beefburger = beefburgerfactory. getfood ();

Beefburger. Get ();

 

}

}

The output result is as follows:

Get a chicken hamburger

Get a beef burger

Advantages and disadvantages of the factory method model: 

Advantage: the Core of the factory method class is an abstract factory class. All specific factory classes must implement this interface. To add a new product object for system expansion, you only need to add a specific object and a specific factory object. The original factory object does not need to be modified or the client needs to be modified, this is in line with the "open-closed" principle.

Disadvantage: when using the factory method mode, the client needs to decide which specific factory to instantiate. That is to say, the factory method mode transfers the internal judgment logic of the simple factory mode to the client code. In addition, additional code is required to use this mode, resulting in increased workload.

Introduction to the practical application of the factory method mode: 

The factory method solves the problem of creating the same series of products and satisfies the "open and closed principle". This requires that when you create the same series of products, the factory method mode is often better than the simple factory mode, especially for large and complex systems.

Tip: 

The factory method solves the shortcomings of the simple factory mode. When adding a product, you only need a specific product and a factory class for creating the product, which has very good maintainability. But it also increases the amount of code and workload. However, the amount of added code is not large.

Note: This document references and uses free and open images and content on the Internet and is released in a free and open manner, hoping to contribute to the mobile Internet and the smart phone age! This document can be reproduced at will, but cannot be used for profit.


Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.