Factory method Mode
Return to the design mode catalog
Read the catalogue:
- Simple Factory mode
- Introduced
- UML Class Diagram
- Reference Code
- Summarize
- Factory method Mode
- Introduced
- UML Class Diagram
- Reference Code
- Summarize
Preface:
"Big talk design mode" There is a section called ' Movable type, object-oriented ', told a small story, the effect is as follows:
In the Three Kingdoms period, Caocao led the army stationed in Chibi. Military ship connected, imposing magnificent, see to extinguish the East Wu, unify the world, Caocao very yue, so big feast courtiers. At dinner Cao Poetic Dafa, don't feel Yin Way: "Drink singing, life is really cool." ......"。 "The Prime Minister good poem!". So a vassal fast life printing craftsmen rigid printing, in order to spread the world.
A look at the sample, the feeling is not good, the way: "Drink and sing this words too vulgar, should be ' complaining ' better!" ", so this minister on the fate of the craftsmen to come again, this craftsman overnight work in vain, had to re-engraved.
Sample chapter again come out please Cao, Cao carefully a product, think or bad, said: "Life really cool too direct, should change the language only enough artistic conception, change to ' complaining life geometry?" ... '. When the courtiers tell the craftsmen, the craftsmen fainted ...
The problem here is that the three-phase printing has not been invented, so when the word changed, it must be the entire plate re-engraved! If you have movable printing, you only need to change four words, the rest of the work is not white.
First, we need to change the word to be changed, this is maintainable ; Second, these words are not useless this time, can be reused in later printing, this is reusable; the third poem to add words, just another inscription to add, which is extensible The arrangement of the fourth word may actually be horizontal, so it is flexible to simply move the movable character to meet the arrangement requirement. When writing code, consider encapsulation, inheritance, multi-state to reduce the coupling degree of the program, using object-oriented thinking to make the program more flexible, easy to modify, and easy to reuse.
Well, say so much, I believe we have a little feeling about the design pattern. Yes, design patterns are designed to make our code more flexible, scalable, maintainable, and reusable. Now let's summarize it from the factory model!
first, simple Factory mode
1. Introduction
Let's talk about the simple factory model before we summarize the factory model. The Simple factory model (aka Static Factory method) is not one of the 23 design modes of GOF. This mode gives the responsibility for creating objects to a factory object that provides a static public method to provide a service to the generated object, and the logic of all generated objects is contained in the static method and is not visible to the outside. Simple factories are the best-understood model in the factory model, and can be seen as the basis for all plant models.
2.UML class Diagram
Pretend there's a class diagram here.
3. Reference Code
This is the client, public class client {public static void main (string[] args) {//client only needs to pass in the required product type to get the corresponding product, the user does not need to know the details of creating the product Product = Simplefactory.create ("A");//Product Product = Simplefactory.create ("B");//call to generate the product's display price method Product.showprice ( );}} /** * Abstract Product Role * * @author Ice_melt * */interface Product {//Show price public void Showprice ();} Specific product AClass Concreateproducta implements product {@Overridepublic void Showprice () {System.out.println ("This is a product, Price is 10RMB, very cheap ");}} Specific product Bclass CONCREATEPRODUCTB implements product {@Overridepublic void Showprice () {System.out.println ("This is a B product, The price is 600RMB, very expensive ");}} /** * Factory Role (that is, the normal class provides a way to create other classes) * * @author Ice_melt * */class simplefactory {/** * Simple factory is generally a static method, which contains the necessary logical judgments, to create a specific product based on client conditions Object * <br><b> Anatomy:</b> * <br> products are now based on <code>Product<code> interface subclass, if Add product, inheritance system no problem * <br> But the factory generation logic needs to be modified (adding if branch judgment logic), which violates the "open closure principle" */public static Product Create (String type) {if ("A". Equals (type)) { return new Concreateproducta ();} else if ("B". Equals (type)) {return new CONCREATEPRODUCTB ();} else {new runtimeexception (type + "product type temporarily cannot be produced, please contact the manufacturer!) ");} return null;}}
4. Summary
The advantage of the simple factory model is that it separates the creators and users of the products and facilitates the optimization of the software system structure. Limitations are not scalable when there is a need to change the code.
Back to Top
Second, the factory method model
1. Introduction
Factory method Mode, also known as polymorphic Sex Factory. This pattern defines an interface for creating an object, allowing subclasses to decide which product object to instantiate. the factory method defers the instantiation of a class to its subclasses.
2.UML class Diagram
Pretending to have a class diagram
3. Reference Code
The first is the abstract product class:
/** * Product Abstraction * * @author Ice_melt * */public abstract class Abstractproduct {public abstractproduct () {}//All products have a way to show it externally public abstract void display ();
Three products in the basic abstract product Category:
Products--car public class Carproduct extends Abstractproduct {@Overridepublic void display () {System.out.println ("I have four wheels, Running fast on Land ");}}
Product--Aircraft public class Airplaneproduct extends Abstractproduct {@Overridepublic void display () {System.out.println (" I have two wings, can fly in the Sky ");}}
Product--Ship public class Shipproduct extends Abstractproduct {@Overridepublic void display () {System.out.println ("I am in the sea, Fast ");}}
Then the factory interface:
/** * A factory interface, responsible for defining the production of product objects * (factory interfaces can also be implemented in an abstract way) * @author Ice_melt * */public interface Ifactory {/* * * * Create a Product object */public Abstractproduct produceproduct ();}
Factory interface of three specific factories, each factory responsible for the production of a product:
Car factory, production car public class Carfactory implements Ifactory {@Overridepublic abstractproduct produceproduct () {return new Carproduct ();}}
Aircraft Factory, production aircraft public class Airplanefactory implements Ifactory {@Overridepublic abstractproduct produceproduct () {return New Airplaneproduct ();}}
Ship factory, production ship public class Shipfactory implements Ifactory {@Overridepublic abstractproduct produceproduct () {return new Shipproduct ();}}
Client code:
/** * Client code * @author Ice_melt * */public class Client {public static void main (string[] args) {//Here you can write the full path class name of the factory class into the project's configuration file and add a method to read the configuration string factoryconfig = Readconfig (); ifactory factory;try {//client code is only coupled to the two top interfaces of abstract factory and abstract product,//Add a new product to the background, You only need to increase the product's factory class at the same time,//You do not need to modify any existing code factory = (ifactory) class.forname (factoryconfig). newinstance (); Abstractproduct Product = factory.produceproduct ();p roduct.display ();} catch (Exception e) {//exception handling E.printstacktrace ();}} public static String Readconfig () {//can write the full path of the factory class name to the configuration file so that the client does not need//change the code, just configure it to complete the display demand without the product return " Com.icemelt.designpattern.factorymethod.AirplaneFactory ";}}
4. Summary
Factory method first need to block the specific implementation of the Product class, the product class how to change, the caller does not need to care, just care about the interface of the product class, usually the interface is relatively stable, as long as this interface does not change, then the upper layer of the system will not change (this is also the benefits of interface-oriented programming). Second, we need to block the concrete implementation of factory methods, the same reason. Then we can enjoy the benefits of the factory approach to the code's flexibility: At this point all client code is only related to two abstract classes (or interfaces), adding that the product needs only to complete the coding of the product and the corresponding factory method to complete the demand increase (no need to modify the client code and the existing code in the background, Customer needs new features just modify configuration
Usually the business logic in the actual application is more complex, the product class may not have a unified interface (and may be a legacy of historical reasons), this time need to find a way to add a unified indirect relationship before continuing to apply this mode.
Back to Top
Java Design pattern: Factory method Mode (Factory methods)