Factory Method Model Introduction
sometimes, because of the diversification of products, but the function of the product has some kind of common connection. We want to define a common interface for creating product objects, and let subclasses decide how to implement this functionality. Then we define a "factory" for the production of the product, and all the products will be produced from the plant, so that the details of the construction of the product are separated from the factory, so that the details of the product are encapsulated, and the scalability of the product is strong. So, this design pattern we call the factory method pattern. Concrete examples are many, such as last year's face Meng software burst red, which applied to the factory method model to give users a variety of face shape.
Factory Method Pattern Classification
According to my personal summary, I think the factory method pattern is divided into four types, and their specific differences are shown in the following table:
static mode |
static methods are used in the factory to create individual products directly |
Normal Mode |
The factory uses the If-else statement to judge the user's needs and then produce the product |
mapping Mode |
the factory uses Key-value to read the configuration file to map the product type and then produce the product |
Reflection Mode |
examples of products used for reflection production in factories |
code implementation of the factory method pattern Common Code Section
now we use to send text, send pictures, send video three functions to simply explain the factory method mode, of course, this example does not go to specific implementation how to send text, pictures, videos and other content, just as a template to demonstrate.
first, we consider that all three functions have one thing in common, that is, they all have the ability to send this behavior, so the most important difference between an interface and an abstract class in Java is that an interface is an abstraction of the behavior, whereas an abstract class is an abstraction of a class, and in a scenario with the same behavior, we prioritize defining an interface to constrain The equivalent of assigning them a principle that must implement the behavior (function) defined in the interface.
Therefore, it is necessary to design a common interface sendable, in which a method send () is defined, which is a function that subclasses must implement.
Package Com.factory.factorymethod;public interface Sendable {public void Send ();}
Next, write three specific products, namely text, pictures, video.
Send text:
Package Com.factory.factorymethod;public class Textsender implements sendable {@Overridepublic void send () { SYSTEM.OUT.PRINTLN ("Send Text");}}
Send Picture:
Package Com.factory.factorymethod;public class Photosender implements sendable {@Overridepublic void send () { System.out.println ("Send Picture");}}
Send video:
Package Com.factory.factorymethod;public class Videosender implements sendable{@Overridepublic void Send () { SYSTEM.OUT.PRINTLN ("Send Video");}}
The above is the public part of the four different design methods, namely the product realization part, therefore, regardless of which method, the product realization and the production is separates.
each of the four different plant design methods is described below.
Factory Method Mode-Normal mode
The common pattern is to use traditional if-else in the factory to determine the user's needs. As shown in the following code:
Package Com.factory.factorymethod;public class Senderfactory {public sendable produce (String type) { if ("text"). Equals (type)) { return new Textsender (); } else if ("Photo". Equals (Type)) { return new Photosender (); } else if ("video". Equals (Type)) { return new Videosender (); } else { System.err.println ("No such Product"); return null;}} }
Factory Method Mode--mapping mode
Mapping mode uses a configuration file to handle key-value pairs, the advantage is that users do not need to remember too many product class names, just remember the keywords can be, the factory will automatically map the past. The code is implemented as follows:
Package Com.factory.factorymethod;import Java.io.inputstream;import Java.util.enumeration;import java.util.HashMap Import Java.util.map;import Java.util.properties;public class Senderfactory {public sendable produce (String key) {try {Propertiesreader Propertiesreader = new Propertiesreader (); Map<string, string> properties = Propertiesreader.getproperties (); String className = Properties.get (key); Sendable sender = (sendable) class.forname (className). newinstance (); return sender;} catch (Instantiationexception | illegalaccessexception| ClassNotFoundException e) {e.printstacktrace ();} return null; }}class propertiesreader {public map<string,string> getProperties () {Properties Properties = new Properties (); map<string, string> hashMap = new hashmap<string,string> (); try {InputStream Resourceasstream = This.getclass (). getResourceAsStream ("Type.properties");p roperties.load (Resourceasstream); enumeration<?> propertynames = Properties.propertynames (); while (PropertYnames.hasmoreelements ()) {string key = (string) propertynames.nextelement (); String property = Properties.getproperty (key); Hashmap.put (key);}} catch (Exception ex) {ex.printstacktrace ();} return hashMap;}}
The configuration file used in the above code is type.properties, which reads as follows:
t=com.factory.factorymethod.textsenderp=com.factory.factorymethod.photosenderv= Com.factory.factoryMethod.VideoSender
Factory Method Mode-Reflection mode
Reflection mode is actually similar to the above one method, but less configuration files, and no keyword, you need to provide a method name, the code is as follows:
Package Com.factory.factorymethod;public class Senderfactory {public sendable produce (String className) { try { Sendable sender = (sendable) class.forname (className). newinstance (); return sender;} catch (Instantiationexception | illegalaccessexception| ClassNotFoundException e) {e.printstacktrace ();} return null; } }
Factory Method Mode-static mode
Static mode, as the name implies, static creation of products in the factory, do not need to create factory objects, this pattern is more extensive, the code example is as follows:
Package Com.factory.factorymethod;public class Senderfactory {public static sendable Producetextsender () { return New Textsender (); } public static sendable Producephotosender () { return to new Photosender ();} public static sendable Producevideosender ( { return new Videosender ();} }
Factory Method Model Summary
When there are a large number of products that need to be created and have some common behaviors, consider using Factory mode to separate the product implementation details. Of these four methods, the most common is the static creation method, the other three may be due to the parameter pass error, cause cannot be created, need to be familiar with the specific invocation parameters.
The factory method pattern for Java Design patterns