Java's factory model (ii)

Source: Internet
Author: User

In addition to the methods mentioned above, you can use the reflection mechanism of Java so that the class name can be used to load the required classes. We just need to change the factory class and drive class.

  Fruitfactory.java

 PackageCom.muggle.project;//Fruit Factory Public classFruitfactory { Publicfruitinterface getfruit (String key) {if("Banana". Equals (Key) {            return NewBanana (); }        Else if("Apple". Equals (Key) {            return NewApple (); }        Else {            return NULL; }    }            /*to create an object using the class name*/     Publicfruitinterface Getfruitbyclass (String calssname) {Try{fruitinterface Fruit=(Fruitinterface) class.forname (calssname). newinstance (); returnfruit; } Catch(Instantiationexception | illegalaccessexception |classnotfoundexception e) {            //TODO auto-generated Catch blockE.printstacktrace (); }                return NULL; }}

Using a dynamically loaded method, you can create an object directly with the class name.

Testdrive.java

 PackageCom.muggle.project; Public classtestdrive { Public Static voidMain (string[] args) {//TODO auto-generated Method Stub        /*the original method without Factory mode*///fruitinterface banana=new Banana ();//banana.produce ();//fruitinterface apple=new Apple ();//apple.produce ();        /*the original method of using Factory mode*///fruitfactory Factory =new fruitfactory ();//fruitinterface banana=factory.getfruit ("banana");//banana.produce ();Fruitfactory Factory=Newfruitfactory (); Fruitinterface Banana=factory.getfruitbyclass ("Com.muggle.project.Banana");    Banana.produce (); }}

Factory mode for Java (ii)

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.