Java design mode (ii) Factory mode

Source: Internet
Author: User

Factory mode is the most common pattern for instantiating objects, which is used in place of the new operation. Creating an object in this mode will have some extra action, but it will bring greater scalability and less modification to the system. Typical application of the Spring bean container. Below is a simple example of implementing a factory.

1, animal interface, provide a common method body

 Public Interface Animal {    publicvoid  eat ();}

2. Cat class, inherit animal interface, realize cat's Eat method

 Public class Implements Animal {    publicvoid  eat () {        System.out.println ("cat is eating ...");}    }

3, dog, inherit the animal interface, realize the dog's Eat method

 Public class Implements Animal {    publicvoid  eat () {        System.out.println ("The Dog is eating ..." );    }}

4. Factory class

Note two points: 1) The return type is Interface 2) The instantiation of the class is implemented by reflection

 Public classAnimalfactory { PublicAnimal getanimalbyclassname (String className) {Animal a=NULL; Try{a=(Animal) class.forname (className). newinstance (); } Catch(instantiationexception e) {e.printstacktrace (); } Catch(illegalaccessexception e) {e.printstacktrace (); } Catch(ClassNotFoundException e) {e.printstacktrace (); }        returnA; }}

5. Test class

 Public class Model {    publicstaticvoid  main (string[] args) {        new animalfactory ();         = Af.getanimalbyclassname ("Design_pattern.factory.Cat");        A.eat ();         = Af.getanimalbyclassname ("Design_pattern.factory.Dog");        A.eat ();    }}

Java design mode (ii) Factory mode

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.