Design mode: Factory mode

Source: Internet
Author: User

First, the Primer
Ten years ago, there was an outbreak, his family had three cars (Benz, BMW), Audi (Audi) It seems that the person is more patriotic, no Japanese car), but also hired a driver to drive for him. However, the outbreak of the car is always the case: on the Benz and the driver said, "Drive a Mercedes!" "When he was in BMW, he said," Drive a BMW! "When he was in Audi, he said," Open the Audi car! "。 You must say: this man is sick! Why don't you just say drive?! And when the outbreak of the user's behavior in our programming language, we found that the C language has been in this way to the car! Fortunately, this kind of illness can be avoided in the OO language. The following is the Java language based on the introduction of the topic of our article: Factory mode!!

Second, Introduction
Factory mode is primarily an interface for creating objects. The factory model is divided into three categories according to the reference in Java and mode:
1. Simple Factory mode (Factory)
2. Factory mode (Factory method)
3. Abstract Factory mode (Factory)
These three modes are progressively abstracted from top to bottom and more general. There is also a classification method, which is to see the simple factory model as a special case of the factory method pattern, two of which belong to a class. Here are two scenarios for using Factory mode:
1. You cannot foresee what kind of instance you need to create at the time of encoding.
2. The system should not rely on the details of how product class instances are created, combined, and expressed

Three, simple Factory mode
As the name implies, the pattern itself is simple, and is used in the case of simpler business.
It consists of three characters (see the following class diagram for a relationship):
1, factory class role: This is the core of this model, contains a certain business logic and judgment logic. In Java it is often implemented by a specific class.

2, abstract product role: it is generally the specific product inherits the parent class or implements the interface. Implemented in Java by an interface or an abstract class.

3. Specific product roles: the object created by the factory class is an instance of this role. Implemented in Java by a concrete class.

So how does the simple factory model work? Let me give you an example, I think this is much easier to understand than to say a large part of the theoretical word description! Here's a cure for the upstart: P
After using the simple factory model, now the upstart just need to sit in the car and say to the driver: "Drive" on it. To see how this is achieved:

Abstract Product Roles
Specific product roles
。。。 (Audi I will not write: P)
Factory class Roles
public class driver{
Factory method
Note The return type is abstract product role
public static Car Drivercar (String s) throws Exception {
return new BMW ();
Tell the driver I'm riding today.
Next command: Drive

If you put all the classes in a file, do not forget that only one of the classes is declared public. The relationships between classes in the program are as follows:

This is the simple factory model. Here are the benefits:

First, after using the simple factory model, our program is not "sick", more in line with the reality of the situation, and the client is exempt from the direct creation of product object responsibility, but only responsible for "consumption" products (as the upstart).
Below we analyze the Simple Factory mode from the opening and closing principle. When the upstart adds a car, as long as the contract is in line with the abstract product, then it can be used by the customer if the factory is informed. Then for the part of the product, it is in line with the opening and shutting principle-open to the expansion, the modification closed; but the factory part seems to be not ideal, because each additional vehicle, must add the corresponding business logic and the judgment logic in the factory class, this obviously violates the opening and closing principle.
For such a factory class (in our case the driver master), we call it the Almighty or the God class.
Our example is the simplest case, and in practical applications it is possible that the product is a multi-layered tree structure. Since there is only one factory class in the simple factory model that corresponds to these products, this may break our God class and then spoil our lovely programmer: (
As I mentioned earlier the simple factory model applies to the case where the business will be simple. The complex business environment may not be very adaptable. This should be done by the factory method mode!!

Four, factory method mode
Let's take a look at its composition:
1, Abstract Factory role: This is the core of the factory method pattern, it is not application-independent. is the interface that the specific factory role must implement or the parent class that must inherit. In Java it is implemented by an abstract class or interface.
2. Specific factory role: it contains code related to the specific business logic. Called by the application to create an object that corresponds to a specific product. In Java it is implemented by a specific class.
3, abstract product role: It is the specific product inherits the parent class or implements the interface. In Java, there are generally abstract classes or interfaces to implement.
4. Specific product role: The specific factory role the object that is created is an instance of this role. Implemented in Java by a specific class.
To use a class diagram to clearly represent the relationship between them:

We're going to use a complete example to see how the various roles in the factory model are coordinated. In the words of the upstart business more and more, their car is more and more. This can be bitter the driver master, what car it must remember, maintenance, all must go through him to use! So the nouveau riche sympathy he said: "Look at you and me for so many years, you do not have to work so hard, I assign you a few staff, you just keep them in mind!" As a result, the management of the factory method pattern arose. The code is as follows:
Abstract product roles, specific product roles similar to the simple factory model, just become more complex, here slightly.

Abstract Factory role
Mr. Upstart, please.
Driver Driver = new Benzdriver ();

The factory method uses an abstract factory role as the core instead of using a specific class as the core in a simple factory pattern. Let's take a look at what the factory approach model brings to us. Use the open and close principle to analyze the plant method model. When a new product (ie, the upstart car) is produced, it can be used by the customer instead of modifying any existing code as long as it is generated according to the contract provided by the abstract product role and the abstract factory role. It seems that the factory method mode is completely in line with the open and closed principle!
Using the factory approach pattern is sufficient to meet most of the business requirements that we may encounter. But when the product variety is very long, there will be a lot of corresponding factory class, this should not be what we want. So I suggest that in this case, the simple factory model combined with the factory method pattern should be used to reduce the factory class: The Simple factory pattern is used for similar species on the product tree (which is usually brothers in the leaves of the tree).
Of course, special treatment is special: There are different product trees in the system, and there are product families on the product tree, then the abstract Factory mode may be used in this case.

V. Summary
Let's take a look at the simple factory model, the factory method model to enlighten us:
If we do not use Factory mode to implement our example, perhaps the code will be much less-just to implement the existing car, do not use polymorphism. But on maintainability, scalability is very poor (you can imagine adding a car to affect the class). So in order to improve scalability and maintainability, it is worthwhile to write more code.

VI. Abstract Factory mode
First come to know what is the product family: in the different product hierarchy structure, the function of the product group of related products. I have to admire you if you can clearly understand this concept by looking at this sentence. Let's use an example to illustrate it in a figurative way.

The Bmwcar and Benzcar in the figure are two product trees (product hierarchies), and Benzsportscar and Bmwsportscar are a product family. They can all be put into the sports car family, so the function is connected. Similarly Bmwbussinesscar and Benzsportscar are also a product family.
Back to the topic of the abstract product model, so to speak, it differs from the factory method pattern in the complexity of the object that needs to be created. and the abstract factory model is the most abstract and most general of the three. Abstract Factory mode is intended to provide an interface to the client to create product objects in multiple product families. Also, use the abstract Factory mode to meet the criteria:
1. There are multiple product families in the system, and the system may only consume one product at a time
2. When used in conjunction with products belonging to the same product family.
Take a look at the various roles of the abstract Factory model (as in the factory approach):
Abstract Factory Role: This is the core of the factory method pattern, and it is not application-agnostic. is the interface that the specific factory role must implement or the parent class that must inherit. In Java it is implemented by an abstract class or interface.
Specific factory role: It contains code that is relevant to the specific business logic. Called by the application to create an object that corresponds to a specific product. In Java it is implemented by a specific class.
Abstract product Role: It is the parent of a specific product inheritance or an interface implemented. In Java, there are generally abstract classes or interfaces to implement.
Specific product roles: the object created by the specific factory role is an instance of this role. Implemented in Java by a specific class.

I have seen the first two patterns, the coordination between the various roles of this pattern should have a number of hearts, I will not cite specific examples. Just be sure to meet the criteria for using the abstract Factory mode Oh, or even if there are multiple product trees, there are product families, but not used.

Simple Factory mode

1. Purpose
The factory model is dedicated to instantiating a large number of classes that have common interfaces, without having to know in advance which class to instantiate each time. It defines an interface for creating objects, and subclasses decide which class to instantiate.
2. Structure of the Simple factory model

3. A simple example of Java code
  1. Product interface
  2. Public interface Product {
  3. public void GetName ();
  4. }
  5. Specific Product A
  6. public class ProductA implements Product {
  7. public void GetName () {
  8. System.out.println ("I am ProductA");
  9. }
  10. }
  11. Specific Product B
  12. public class PRODUCTB implements Product {
  13. public void GetName () {
  14. System.out.println ("I am PRODUCTB");
  15. }
  16. }
  17. Factory class
  18. public class Productcreator {
  19. Public Product createproduct (String type) {
  20. if ("A". Equals (type)) {
  21. return new ProductA ();
  22. }
  23. if ("B". Equals (type)) {
  24. return new PRODUCTB ();
  25. } else
  26. return null;
  27. }
  28. public static void Main (string[] args) {
  29. Productcreator Creator = new Productcreator ();
  30. Creator.createproduct ("A"). GetName ();
  31. Creator.createproduct ("B"). GetName ();
  32. }
  33. }
4. Summary of the scope of application of the factory model
• You cannot foresee the instances of which classes need to be created when coding.
• A class uses its subclasses to create objects.
• The developer does not want to create an instance of which class and how to create an instance of the information exposed to external programs.

Abstract Factory mode

1. Abstract factory patterns can be said to be an extension of the simple factory model, where the main difference is in the complexity of creating objects.
In abstract Factory mode, an abstract product may be one or more, thus constituting one or more product families. In the case of only one product family, the abstract factory pattern actually degrades to the factory method pattern.
2. Structure of the abstract factory model

3. A simple example

Java code
  1. Product Plant Interface
  2. Public interface Plant {
  3. }
  4. Specific product PLANTA,PLANTB
  5. public class PlantA implements Plant {
  6. Public PlantA () {
  7. System.out.println ("Create PlantA!");
  8. }
  9. public void dosomething () {
  10. System.out.println ("PlantA do something");
  11. }
  12. }
  13. public class Plantb implements Plant {
  14. Public Plantb () {
  15. System.out.println ("Create PLANTB!");
  16. }
  17. public void dosomething () {
  18. System.out.println ("Plantb do something");
  19. }
  20. }
  21. Product Fruit Interface
  22. Public interface Fruit {
  23. }
  24. Specific product FRUITA,FRUITB
  25. public class Fruita implements Fruit {
  26. Public Fruita () {
  27. System.out.println ("Create Fruita!");
  28. }
  29. public void dosomething () {
  30. System.out.println ("Fruita do something");
  31. }
  32. }
  33. public class FRUITB implements Fruit {
  34. Public Fruitb () {
  35. System.out.println ("Create FRUITB!");
  36. }
  37. public void dosomething () {
  38. System.out.println ("FRUITB do something");
  39. }
  40. }
  41. Abstract Factory method
  42. Public interface Abstractfactory {
  43. Public Plant createplant ();
  44. Public Fruit createfruit ();
  45. }
  46. Specific Factory methods
  47. public class Factorya implements Abstractfactory {
  48. Public Plant createplant () {
  49. return new PlantA ();
  50. }
  51. Public Fruit Createfruit () {
  52. return new Fruita ();
  53. }
  54. }
  55. public class Factoryb implements Abstractfactory {
  56. Public Plant createplant () {
  57. return new PLANTB ();
  58. }
  59. Public Fruit Createfruit () {
  60. return new FRUITB ();
  61. }
  62. }
4. Summary
You should consider using the abstract factory pattern in the following cases.
First, a system should not depend on the product class instances being created, composed, and represented in detail. This is important for all forms of Factory mode.
Second, the product of this system has more than one product family.
Thirdly, products belonging to the same product family are designed to be used together. This constraint must be reflected in the design of the system.
Finally, different products appear in a series of interfaces, so that the system does not depend on the details of the implementation of the interface.
The second and third condition is the key condition for the use of abstract factory models rather than other forms of Factory mode.

Design mode: 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: 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.