Factory design patterns used in Java development

Source: Internet
Author: User

 PackageGongchangdemo;/** Use more of a design pattern in Java development: Factory mode: is a transition side * through the over-end to get interface instantiation object, this transition is called Factory Factory * This mode is mainly to solve the modification of subclasses, you must modify the Main method, And the main method is mainly the client, the client * often changed to go not very good, introduced: Factory mode*/ Public classGongchangdemo { Public Static voidMain (String args[]) {//the GetInstance method is static, so it can be called directly with the class name//Fruit F =null; //f = factory.getinstance ("Apple"); //f.eat (); //It says that Apple is fixed and can be used to initialize parameters by selecting any subclass to markFruit F =NULL; F= Factory.getinstance (args[0]); if(f!=NULL) {f.eat (); }    }}//Write an interfaceInterfacefruit{//write an abstract class to eat     Public Abstract voideat ();}//write a subclass to implement fruitclassAppleImplementsfruit{ Public voideat () {System.out.println ("I'm eating an apple."); }}//write another subclass to implement fruitclassOrangeImplementsfruit{ Public voideat () {System.out.println ("I'm eating oranges."); }}//Write a transition-class factory, get the instantiated object of the interfaceclassfactory{//returns the fruit type, so it is decorated with fruit     Public StaticFruit getinstance (String classname) {//Initialize FirstFruit F =NULL; //the passed parameter is compared with the subclass name .        if("Apple". Equals (classname)) {f=NewApple (); }        if("Orange". Equals (classname)) {f=NewOrange (); }        returnF; }    }

Factory design patterns used in Java development

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.