The 1th chapter of the design pattern-factory method Mode (Java implementation)

Source: Internet
Author: User

The 1th chapter of the design pattern-factory method Mode (Java implementation)

  "I'll go First", "No, hubby, I'll go first!" ”。 Far heard a few people, oh no, is the factory method mode and abstract factory model two small couple in quarrel, Nikki Sister, not to eat, who first come not all the same (foodie of the World ~). "Abstract Factory mode, hurriedly self-introduction, factory method mode, you as a man, to understand the gentleman demeanor, Lady first understand not understand, later come again, anxious what." "(voiceover: Fish elder brother, this is my family's ancestral snacks, and my father's good wine Blablabla)," Ah, that abstract factory model, aunt shouted you home for dinner. "Oh, I'll go back and wait for me." "Factory method, hurriedly." "Wait, fish brother, last time I haven't finished, give me a minute first, let me put the application scenario to say." "Yes, well," (voiceover: The author of the old Beijing candied fruit and other snacks in his mouth has been dragged away by the crowd) 、、、

Benefits: The application scenario for Singleton mode

In the following case, it's my turn to play:

    • When there is only one instance in a class and the customer can access it from a well-known access point.
    • When this unique instance should be extensible by subclasses, and the customer should have no need to change the code to be able to use an extended instance.

  Well, about my end of this, the factory method, you come.

Self-introduction of factory Method mode

Good mode is me, I am a good model (eyebrow): Factory method ~ Everyone applauded, (PS: Wait a few seconds, silence, the masses: no gentleman is good man, I go, needs bark), cough, that, as a developer, the daily development of my exit rate is very high, often can see my figure, The definition is as follows: Define an interface for creating a object,but let subclasses decide which class to instantiate. Factory Method lets a class defer instantiation to subclasses. You know what that means? PS: Even if English is good, but your pure chinglish let us also listen to be drunk. I do not know, I will translate for you, the meaning of this sentence is: Define an interface for creating objects, let subclasses decide which class to instantiate. The factory method defers the instantiation of a class to its subclasses. Still don't understand? That speaks:

  

is the general class diagram of the factory method pattern.

In my model, the abstract product class product is responsible for defining the commonality of the product, the realization of the most abstract definition of things, creator for the abstract creation of the class, that is, the abstract factory, how to create a product class is specific to the implementation of the factory Concretecreator complete. My descendants are more (PS: that is more varieties), good self introduction to this end, the following is the time to show my excellent character.

Self-analysis of factory method patterns

My biggest drawback is that no shortcomings, perfect is not good, want to humble a bit can not, do not believe? Well, then you're fine:

    • First of all, the packaging is better, so the factory method makes the code structure clear, conducive to maintenance.
    • Secondly, extensibility is also very good, want to add a product, a problem, do not refactor, not complex, only need to expand a factory class can achieve embrace change.
    • Again, can block the specific implementation of the Product class, the use of people do not need to worry about how to achieve, as long as the interface can be called, as long as the interface is inconvenient, then the upper module will not change.
    • Finally, I'm a typical decoupling framework that conforms to the legendary Dimitri rule and relies on the inversion principle.

  Shortcomings, really did not say.

"You cheat, if you do not say, I will take you peek * * *", "Stop, stopped, I said, I just made a joke, why take it seriously, as the saying goes, the model is not a sage, who can have no shortcomings." ”

Disadvantages:

    • A potential disadvantage is that customers may have to create creator subclasses just to create a specific Concreteproduct object.

Implementation of factory method model

  What, still do not understand, well, served you, really and Guo Jing as stupid, then you watch, I do show you. Well, know the author is a pure foodie, oh no, food lovers, then come to a gourmet factory.

1  Public Interface food{2      Public void Createfood (); 3 }

  This food interface is a generic term for foods, and each food has a way of making it.

1  Public class Implements food{2      Public void Createfood () {3         System.out.println ("I am the delicious old Beijing candied fruit ~"); 4     }5 }

  The above code is the production of old Beijing candied fruit.

1  Public class Implements food{2      Public void Createfood () {3         System.out.println ("I Am the delicious Dragon Hot strips ~"); 4     }5 }

  Is the legend of the Dragon Hot Bar, OK now everything has, only owed the East wind, wrong, Dongfeng useless, is only owed to the factory. So long as the foodie author orders The factory, then you can produce delicious snacks to come.

Here is the implementation of the abstract factory:

1  Public Abstract class abstractfoodfactory{2      Public Abstract extends Food> T Createfood (class<t> c); 3 }

You can see how the food factory produces the food. The input parameter is the implementation class of the foods interface, which is consistent with the class diagram. Here we use generics, by defining generics, to restrict the input of createfood, must be class, must be food class.

The following is the implementation of the Gourmet Factory:

1  Public classFoodfactoryextendsabstractfoodfactory{2      Public<textendsFood> T Createfood (class<t>c) {3Food food =NULL;4         Try{5Foor =(T) Class.forName (C.getname ()). newinstance ();6         }7         Catch(Exception e) {8SYSTEM.OUT.PRINTLN ("Food production failed!") ");9         }Ten         return(T) food; One     } A}

  Finally, the test class, the production of food for fish Brother practical ~

1  Public classauthor{2      Public Static voidMain (string[] args) {3Abstractfoodfactory foodfactory =Newfoodfactory;4 5         //the author's favorite gourd6Food Tanghulu = Foodfactory.createfood (Tanghulu.class);7 Tanghulu.createfood ();8 9         //The author likes the Guardian Dragon Spicy bar ~TenFood Latiao = Foodfactory.createfood (Latiao.class); One Latiao.createfood (); A     } -}

  With this gourmet factory, the author no longer have to worry about snacks ~ So, my factory method mode is finished, the following in order to no longer perform the singleton pattern that guy's mistake, I'm going to start to introduce when it should be my turn on the camera, "Alas, what do you do, abstract Factory mode, why, my ears, to drop ~", How dare you force fish brother to take your bribe, then force him to deceive me, let you first introduce, go, go back to kneel keyboard. "Wife, I was wrong, you let me finish this point again, ah, you all help 、、、 help 、、、 i 、、、、", (PS: Look at the farther away of the small couple, the author suck Smack, touch the small belly of the drum up, from the back leisurely walk), "Hiccup ~", the amount of that, because the factory method mode for some reason to leave, The application scenario is placed next time as welfare to send, really, even the wife's words are not listening, the kneeling keyboard (PS: The author broken read), as for the factory method mode and abstract factory model between the story, cough, predict funeral how, and listen to tell.

The first chapter: the sequence of design patterns-UML class diagram that thing.

The second: the No. 0 Chapter of the design pattern-a singleton pattern (Java implementation)

Reference book: Gof Design patterns:elements of reusable object-oriented software

Qin Xiaobo's "The Zen of Design Patterns second Edition"

PS: This blog welcome forwarding, but please specify the blog address and author ~

Blog Address: http://www.cnblogs.com/voidy/

  Blog:http://voidy.gitcafe.com

<. ))) ≦

The 1th chapter of the design pattern-factory method Mode (Java implementation)

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.