[Original · tutorial · serialization] "android big talk Design Model"-design mode Creation Model Chapter 1: simple factory Model

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 the best Android Application in China.ProgramDevelopment institutions provide the best Android enterprise application development training services.

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

Simple factory Mode Love at first sight 

Simple factory Model Application Scenario example: 

"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 ",..., Everyone ordered their favorite food, and then Gg and mm added a few more portions of food respectively. gg handed the order to the front-end staff and the waiter cleared all expenses, gg immediately fainted ^_^. It seems that the cost of living for a month is indeed ruined, but it is still excited, smiling and coming to the beauty of the crowd, sitting there waiting to slowly enjoy the food, the rest is handed over to the waiter...

Simple factory mode explanation: 

Simple factory pattern is an innovative class mode, also known as static factorymethod pattern. It is used to create instances of other classes by defining a specific class, the created instance usually has a common parent class.

Simple factory ModelUMLFigure: 

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

Creator: this is the core of the simple factory model. It is responsible for creating the internal logic of all classes. Of course, the factory class must be called by the outside world to create the required 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 simple factory models:

The simple factory mode solves the problem of how to instantiate a suitable object.

The core idea of the simple factory model is: there is a dedicated class responsible For the instance creation process.

Specifically, products are a collection of classes, which are an object tree derived from an abstract class or interface. The factory class is used to generate a suitable object to meet the customer's requirements.

If the simple factory model involves no common logic between specific products, we can use interfaces to assume the role of abstract products. If there is a functional logic between specific products or, we must extract these common things and put them in an abstract class so that the specific product can inherit the abstract class. To achieve better reuse, common things should always be abstracted.

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

Simple factory Mode Application Scenario Analysis andCodeImplementation: 

Gg invited his girlfriend and many beautiful women to dinner, but Gg could not cook or cook well. This shows GG does not need to create various food objects by herself; all beautiful women have their own interests. After arriving at McDonald's, they can simply order what they like. McDonald's is a factory that produces all kinds of food. At this time, GG doesn't have to do it by herself, you can also invite so many beautiful women to dinner. All you need to do is pay O (shopping _ shopping) O Haha ~, The UML diagram is as follows:

The implementation code is as follows:

Create a new interface for food:

PackageCom. diermeng. designpattern. simplefactory;

 

/*

* Abstract interfaces of Products

*/

Public InterfaceFood {

/*

* Get the corresponding food

*/

Public VoidGet ();

}

Next we will build a specific product: Chicken and fries

package COM. diermeng. designpattern. simplefactory. impl;

Import COM. diermeng. designpattern. simplefactory. food;

/*

* chicken implementation of abstract product interfaces

*/

Public class mcchicken implements food {

/*

* Get a wheat-flavored chicken

*/

Public void get () {

system. out . println ("I want a chicken ");

}

}

PackageCom. diermeng. designpattern. simplefactory. impl;

ImportCom. diermeng. designpattern. simplefactory. Food;

 

/*

* Implement the abstract product interface of French fries

*/

Public ClassChipsImplementsFood {

/*

* Get A fries.

*/

Public VoidGet (){

System.Out. Println ("I want a fries ");

}

}

Now we have established a food processing factory:

PackageCom. diermeng. designpattern. simplefactory. impl;

ImportCom. diermeng. designpattern. simplefactory. Food;

 

 

Public ClassFoodfactory {

 

Public StaticFood getfood (string type)ThrowsInstantiationexception, illegalaccessexception, classnotfoundexception {

If(Type. equalsignorecase ("mcchicken ")){

ReturnMcchicken.Class. Newinstance ();

 

}Else If(Type. inclusignorecase ("Chips ")){

ReturnChips.Class. Newinstance ();

}Else{

System.Out. Println ("Oh! The corresponding instantiation class cannot be found! ");

Return Null;

}

 

 

}

}

Finally, we create a test client:

PackageCom. diermeng. designpattern. simplefactory. client;

ImportCom. diermeng. designpattern. simplefactory. Food;

ImportCom. diermeng. designpattern. simplefactory. impl. foodfactory;

 

/*

* Test the client

*/

Public ClassSimplefactorytest {

Public Static VoidMain (string [] ARGs)ThrowsInstantiationexception, illegalaccessexception, classnotfoundexception {

 

// Instantiate various foods

Food mcchicken = foodfactory.Getfood("Mcchicken ");

Food chips = foodfactory.Getfood("Chips ");

Food eggs = foodfactory.Getfood("Eggs ");

 

// Get food

If(Mcchicken! =Null){

Mcchicken. Get ();

}

If(Chips! =Null){

Chips. Get ();

}

If(Eggs! =Null){

Eggs. Get ();

}

 

 

}

}

The output result is as follows:

Oh! The corresponding instantiation class cannot be found!

I want a chicken.

I want a fries.

Advantages and disadvantages of the simple factory model: 

Advantage: the factory class is the key to the entire model. It contains the necessary judgment logic to determine the specific class object to be created based on the information given by the outside world. You can directly create required instances based on the factory class during use without understanding how these objects are created and organized. It is conducive to the optimization of the entire software architecture.

Disadvantage: the factory class integrates the creation logic of all instances, which directly causes all clients to be affected once a problem occurs in the factory; in addition, because the product room in the simple factory mode is based on a common abstract class or interface, when the product type increases, there are different product interfaces or abstract classes, factory products need to determine when to create products of which type. This is confused with the products of which type of product is created. This violates a single responsibility and leads to a loss of flexibility and maintainability of the system. More importantly, the simple factory model violates the principle of "Opening and Closing", that is, the principle that "the system is open to expansion and the system is closed to modification, because the factory class must be modified when I add a new product, and the corresponding factory class needs to be re-compiled.

To sum up, the simple factory model separates product creators and consumers, which is conducive to the optimization of the software system structure. However, because all logic is concentrated in a factory class, there is no high cohesion, it also violates the "open and closed principle ". In addition, the methods of the simple factory mode are generally static, while the static factory method cannot inherit subclass. Therefore, the simple factory mode cannot form an inherited tree structure based on the base class.

Introduction to the practical application of the simple factory model: 

As the most basic and simple design mode, the simple factory mode is widely used. Here we take the JDBC operation database in Java as an example to describe it.

JDBC is a set of database programming interface APIs provided by Sun. It uses Java to provide simple and consistent access to various relational databases. The Java program can execute SQL statements through JDBC to process the obtained data and store the changed data back to the database. Therefore, JDBC is a mechanism for Java applications to communicate with various relational data. When using JDBC for database access, you must use the driver interface provided by the database vendor to interact with the database management system.

To use data, the client only needs to interact with the factory, which greatly simplifies the operation steps. The operation steps are as follows: Register and load the database driver, generally, class is used. forname (); create a connection object with the database; create an SQL statement object preparedstatement (SQL); Submit an SQL statement and use executequery () or executeupdate () according to the actual situation (); display the corresponding results; close the database.

Tip: 

Strictly speaking, the simple factory mode is not a design mode. The simple factory mode is more like a programming habit, which is widely used. However, the lack of a simple factory model in "high cohesion" is even more fatal because it violates the "open and closed principle" in a strict sense ", or provide some support to the "open and closed principle", which makes it very troublesome to add a new product each time, because whenever a new product is added, the factory role must know the product, know how to create the product, and provide it to the client in a good way. In short, each time a new product is added, the factory role must be modified.Source code. Therefore, the simple factory model is not conducive to building a system that is prone to changes. While "demand is always changing", "No software in the world remains the same ". Therefore, you must consider it carefully when using the simple factory model.

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.Benefit.

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.