static method Factory mode

Source: Internet
Author: User

There are three ways to implement a factory pattern, one is to decide which product to create by passing in the name of the parameter, which is a big drawback, that is, if the incoming product name is not carefully mistaken, it is impossible to create the product we want. The other is the method Factory mode, which corresponds to each product in the factory model, there is a method of creation, so that after creating a factory instance, directly through the factory instance can call the corresponding product creation method to create the products we need. However, this factory model needs to create a factory instance, a factory may use a lot of places, have been creating instances is not good, so there is a static method Factory mode.

Package mode.factory.static_method_factory;/** *  Abstract Fruit Class (a factory, production is certainly a certain category of the same product, we are here is a fruit processing plant) *  * */public Interface Fruit {/* fruit can be eaten by */public void eat ();}

Here are the specific implementations of the two fruit categories:

Package Mode.factory.static_method_factory;public class Apple implements Fruit {@Overridepublic void eat () { System.out.println ("Eat Apples");}}

Package Mode.factory.static_method_factory;public class Orange implements Fruit {@Overridepublic void eat () { System.out.println ("Eat Oranges");}}

With these two kinds of fruits we can create our factory to produce these fruits.

Package Mode.factory.static_method_factory;public class Fruitfactory {/* Apple production line */public static Fruit getapple () {return n EW Apple ();} /* Orange production line */public static Fruit Getorange () {return new Orange ();}}

Factory put into production, produce products directly to try to see;

Package Mode.factory.static_method_factory;public class Test {public static void main (string[] args) { Fruitfactory.getapple (). Eat (); Fruitfactory.getorange (). Eat ();}}


static method 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.