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