The so-called factory model in my eyes, the factory model in my eyes

Source: Internet
Author: User

The so-called factory model in my eyes, the factory model in my eyes

When talking about the design pattern in the software architecture, the first sentence of most people is the factory pattern. Accurately speaking, there are no factory models in the classic 24 design models, but simple factory models, factory method models and abstract factory models. The three are essentially different from each other, A code system formed to solve problems in different fields. I remember that when I first changed my job after graduation, I had a design model problem in an interview. However, at that time, I was too tender and lost. At that time, I knew that there was a design model, because this school does not teach. Since then, I began to study the design model, so I had this series of articles.

Three basic features of object-oriented programming: encapsulation, inheritance, and polymorphism. The concept of simplicity is actually very deep in every feature. Here we will only look at polymorphism. polymorphism refers to the use of the concept of inheritance and the implementation of abstract dependencies. We can look at an example that everyone will encounter when learning programming languages, first, create a base class. You can use an interface to add a method.

Create a SampleBase class with the following code:

 

1 public class SampleBase {2 3     public String getName()4     {5         return this.getClass().toString();6     }7 }

 

Create a category class that integrates the class. The Code is as follows:

1 public class SampleImpl extends SampleBase {2     @Override3     public String getName()4     {5         return this.getClass().toString();6     }7 }

The test code is as follows:

public static void main(String[] args) {            SampleBase base = new SampleImpl();    System.out.println(base.getName());}

Running result:

class com.aspnetdream.test.SampleImpl

  

In fact, I keep remembering one sentence in my mind that the base class Pointer Points to the sub-class application. My Learning career started to get started with C ++, remember this sentence and I think it is a magic weapon to cope with inheritance and polymorphism. Based on the excellent characteristics of programming language, I think about many application scenarios I encountered at work. I used to develop an ERP system for catering. When processing orders, there were many different documents, there are similarities and differences between these documents, such as batching orders and return orders. The two orders are the same in that they are processed for material splitting of business documents, however, the tables stored in the last order are different. That is to say, I need the same code for splitting the two documents. But after this step is completed, the codes are different, use the simple factory mode to solve the problem.

Create the document base class IOrderInfo. Here I define it as an interface, which can be defined as an abstract class or even a class in practical applications.
Create the IOrderInfo interface with the following code:

1 // simple factory Mode interface Definition Layer 2 public interface IOrderInfo {3 public String getOrderInfo (); 4}

After the interface is created in the window, we create the classification class for the batching ticket and return ticket respectively.
OrderMakeCustom for a single type of ingredients. The Code is as follows:

1 // simple engineering interface Implementation Layer consumption order operation class 2 public class OrderMakeCustom implements IOrderInfo {3 4 public String getOrderInfo () 5 {6 return this. getClass (). toString (); 7} 8 9}

Return order class OrderReturnCustom, the Code is as follows:

// Simple factory interface Implementation Layer return order operation class public class OrderReturnCustom implements IOrderInfo {public String getOrderInfo () {return this. getClass (). toString ();}}

The IOrderInfo interface is implemented for both the category classes. If you have a little experience writing it here, you can see it. In actual code calls, you can

IOrderInfo order = new OrderMakeCustom ();

This is a rough practice, but such code is everywhere during project development.
Here, we use a simple factory to implement the new task, and assign the new task to the factory instead of the specific business process code, my personal tasks have the following advantages:
1. The code is neat and easy to maintain. If the entire code is mixed with a lot of new ones, it is quite painful for me to read the code. The consequence of this streamlined code method is that, as soon as the business is complex, everyone starts to go through the maze.
2. Put the code into the factory to prepare for subsequent code upgrades. If I put all the sub-classes implemented by the corresponding interface into an xml file, use reflection to instantiate a specific base class. Is this the prototype of IOC.

Continue with the code and create a Factory. In this class, create different order instances based on different business processes and hand them over to the caller to implement the Code:

1 public class Factory {2 3 // operation class Factory 4 public static IOrderInfo createOrderInfo (EServiceType createType) 5 {6 switch (createType) 7 {8 case Make: 9 return new OrderMakeCustom (); 10 case Return: 11 return new OrderReturnCustom (); 12 default: 13 return null; 14 15} 16} 17}

 

In order to facilitate the creation, I put an enumeration type here. The factory class of a simple factory will use different instance classes according to different enumeration types passed in.

OK. Now a simple factory mode is set up. Let's test and run the test code as follows:

1 public static void main (String [] args) {2 3 SampleBase = new SampleImpl (); 4 System. out. println (base. getName (); 5 6 // instantiate different order operation classes based on different types 7 // ------ simple factory mode (static factory Mode) 8 // return order operation class 9 IOrderInfo order = Factory. createOrderInfo (EServiceType. return); 10 // after obtaining the order, process the order 11 getOrderInfo (order); 12 13 order = Factory. createOrderInfo (EServiceType. make); 14 getOrderInfo (order); 15 16} 17 18 // operate the order Model in the actual project, without worrying about the order type, at the business Implementation Layer, pay attention to the returned order 19 private static void getOrderInfo (IOrderInfo order) 20 {21 System. out. println (order. getOrderInfo (); 22}

 

Running result:

class com.aspnetdream.bussinessImpl.OrderReturnCustomclass com.aspnetdream.bussinessImpl.OrderMakeCustom

 

The IOrderInfo object in the abstract layer is used as the handle. For specific implementation, the factory requests the corresponding implementation layer according to different business requirements. Back to the scenario I first described, we can put the same business in the two types of documents into the abstraction layer, and even at the abstraction layer, we can define the same calling method for different business codes, in this way, your code grade will be much higher! The simple factory mode is also called the static factory mode. It creates implementation layers in a rigid way, but puts all new code into the factory, but you still need to use the selection mode, that is, to tell the factory whether to create A or B. That is why I add enumeration to my code. In fact, there is no major difference between the Code and the specific implementation of new. Therefore, the factory method mode is generated. In my opinion, the application of this model is based on different product operations. When developing a POS backend application, it is all product information, however, the information sent to the POS end is different from the information sent to the mobile phone end. The POS end may have comprehensive information, but the information sent to the Mobile End is relatively small, because in my product, the mobile end only supports Viewing Reports. Here we try to solve this problem using the factory method.
First, create the product's base class, iproduct interface, the Code is as follows:

1 // factory method mode --- abstract role interface 2 public interface iproduct {3 4 public String getPrdName (); 5}

Create different product implementation classes for Pos and mobile terminals, PosProduct and MobileProduct respectively. Code implementation:

// Factory method mode specific role class public class MobileProduct implements iproduct {// implement the abstract role interface @ Override public String getPrdName () {return this. getClass (). toString () ;}// factory method mode --- specific role class public class PosProduct implements iproduct {@ Override public String getPrdName () {return this. getClass (). toString ();}}

Based on the application role, we have created the product Abstract Factory IProductFactory. The Code is as follows:

// Factory method mode ---- abstract Factory public abstract class IProductFactory {public abstract iproduct getProduct ();}

The abstract factory is responsible for returning the abstract role and abstracting the abstract.

If there is abstraction, there is implementation. We need to operate different product information on the POS and Mobile terminals. If so, we have two different business implementation requirements for abstraction, then implement abstraction to create the two implementation factory PosFactory and MobileFactory. The Code is as follows:

1 // factory method mode ---- specific role factory pos product factory 2 public class PosFactory extends IProductFactory {3 4 public iproduct getProduct () 5 {6 return new PosProduct (); 7} 8 9} 10 11 12 // factory method mode --- factory method mode specific products total mobile products factory class 13 public class MobileFactory extends IProductFactory {14 15 public iproduct getProduct () 16 {17 return new MobileProduct (); 18} 19 20}

After this step is created, the basic factory method mode is complete. Next we will test the test code as follows:

1 public static void main (String [] args) {2 3 // ------ factory method mode 4 IProductFactory ifacloud = new MobileFactory (); // The mobile product factory returns the mobile product 5 iproduct prd = ifacloud. getProduct (); 6 System. out. println (prd. getPrdName (); 7 8 ifacloud = new PosFactory (); // return pos product factory return pos product 9 prd = ifacloud. getProduct (); 10 System. out. println (prd. getPrdName (); 11 12} 13 14 // operate the Order Model in the actual project, without worrying about the order type, at the business Implementation Layer, pay attention to the returned order 15 private static void getOrderInfo (IOrderInfo order) 16 {17 System. out. println (order. getOrderInfo (); 18}

Running result:

class com.aspnetdream.driver.productImpl.MobileProductclass com.aspnetdream.driver.productImpl.PosProduct

In my memory, the factory method mode is abstract to abstract, and the Implementation can be implemented infinitely based on specific business needs. Of course, you need an infinite factory to help you achieve it.

  Comparison between simple factory mode and factory method mode:
In my opinion, the simple factory model is the diaosi in the factory model, and the factory method model is Gao fushuai. The biggest feature of the diaosi model is to "hide in the building to form a unified system, regardless of spring, summer, and autumn and winter ", how can we make it out of the outside? What type do you want me to create? I just want to create it for you, at the same time, you must write the type to be created into the factory, that is, a new instance.
However, in the factory method model of Gao fushuai, there are both Niang and Niang. First, at the abstract layer of the factory, you must correspond to the role type of your factory operations, that is to say, the gang you belong to has been basically determined, so roles are generally abstracted, and the type of operations at the factory abstraction layer must also be abstract, "abstract to abstract"-I said it again.
Based on the above statement, the simple factory model is very wild. If you want to create something, I will create it. Whatever you want, this is not much different from the straight line code. The factory method mode is the same, and the code is more complex than the simple factory mode, but it is indeed quite standardized. Based on this mode, code layering is actually quite smooth.

Well, it corresponds to the factory model. As I said just now, you can implement it as much as you want. This is both a benefit and a disadvantage. The Code is limited and the demand is rampant, there is always a time when people turn off the lights, and it is because the implementation is limited, so in the implementation, if you can not implement so much Factory Code is a little concise. As a result, we have produced the abstract factory model, which moves the code that was originally implemented in the factory method model to a unified abstract layer, and then implements the abstraction, see how the code is implemented.
Create the AbstractFactory class of the abstract factory mode. The Code is as follows:

1 // abstract Factory mode -- abstract Factory 2 public abstract class AbstractFactory {3 4 public abstract iproduct createPosProdct (); 5 6 public abstract iproduct createMobileProduct (); 7}

For the Implementation Layer DefaultFactroy of the abstract class, the Code is as follows:

1 // Abstract Factory mode factory Implementation Layer 2 public class DefaultFactory extends AbstractFactory {3 4 public iproduct createPosProdct () 5 {6 return new PosProduct (); 7} 8 9 public iproduct createMobileProduct () 10 {11 return new MobileProduct (); 12} 13}

Well, the abstract factory is ready. The test code below is as follows:

1 public static void main (String [] args) {2 3 // --- Abstract Factory Mode 4 AbstractFactory dfactory = new DefaultFactory (); 5 prd = dfactory. createMobileProduct (); 6 System. out. println (prd. getPrdName (); 7 8 prd = dfactory. createPosProdct (); 9 System. out. println (prd. getPrdName (); 10}

Running result:

class com.aspnetdream.driver.productImpl.MobileProductclass com.aspnetdream.driver.productImpl.PosProduct

I think there are no good or bad Abstract Factory and factory method models. Different application scenarios use different models to solve a problem in our actual work scenarios, it is often used in several modes. The internal code of an application mode may be implemented in other modes. In fact, every one of the twenty-four design patterns is separated from each other, and each of them is very simple. The code above can be understood by everyone, but how to use it is a basic skill, flexible code expansion and application are also a requirement for its own code capabilities.
Now, let's put aside some ideas. Thank you for your advice!

My directory structure:

Finally paste my source code: http://files.cnblogs.com/aspnetdream/factory.rar


Can someone explain to me the so-called factory pattern commonly used in the aspnet project?

The factory model is divided into three types according to the reference in Java and patterns: 1. simple Factory 2. factory Method 3. abstract Factory models are gradually abstracted from top to bottom and more general. In this case, we recommend that you use the simple factory mode and factory method mode to reduce the factory class: that is to say, a simple factory model is used for similar types on the product tree (generally the leaves of the tree are sibling ones. Let's take a look at the various roles of the abstract factory model (similar to the factory method): Abstract Factory role: this is the core of the factory method model and has nothing to do with the application.

The factory model consists of three participants: Abstract Product, factory, and specific Product ). The customer will only see the factory and abstract products.

Public interface Product {
Public String getName ();
}

Public class ConcreteProduct implements Product {
Public String getName (){
Return "Product 1 ";
}
}

Public class Creator {
Public static Product create1 (){
Return new ConcreteProduct ();
}
}

The function of the factory model is to control the method for creating a specific product by the factory class. The customer only needs to know the abstract type of the product.

Who can introduce the advantages of the factory model?

No way wins no way! You don't even have to consider its existence!

The so-called factory must have the processing function! It helps your code design! I personally think he can modularize the code!

If you need a JackJones shirt, you just need to call JackJonesFactory and return one to you! Maybe you need to consider how JackJonesFactory is implemented internally, but it shouldn't be something you should consider when you need a shirt.

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.