Three factory models with advanced features

Source: Internet
Author: User

The simple factory mode is a creation mode, also called the static factory method mode, but not one of the 23 gof design modes. The simple factory mode is determined by a factory object to create a product instance. The simple factory model is the simplest and Practical Model in the factory model family. It can be understood as a special implementation of different factory models.

A dedicated class is used to create instances of other classes. The created instance usually has a common parent class.
We expand from an instance
Now we have an interview question: to use Java to implement a computer console program, we need to input the number calculation and get the result.
The most primitive method of this question:

 


Public class computer {


Public static void main (string [] ARGs ){
Running in = New Processing (system. In );
System. Out. println ("Enter the first number ");
Float firstnum = in. nextfloat ();
System. Out. println ("enter the second number ");

Float secondnum = in. nextfloat ();
System. Out. println ("Enter the operator ");
String countquato = in. Next ();
If ("+". Equals (countquato )){
System. Out. println ("Result:" + (firstnum + secondnum ));

} Else if ("-". Equals (countquato ));{
System. Out. println ("Result:" + (firstnum-secondnum ));

} Else if ("*". Equals (countquato ));{
System. Out. println ("Result:" + (firstnum * secondnum ));

} Else if ("/". Equals (countquato ));{
System. Out. println ("Result:" + (firstnum/secondnum ));


}
}

Although the above method is simple to implement, it does not have the object-oriented feature, and the code scalability is poor. Obviously, it is not the intention of the author to investigate.
So how should object-oriented programming be reflected in the question?
In object-oriented programming languages, everything is an object, so the operator numbers above should also be processed as objects.

Public abstract class operation {

Public abstract float getresult (float firstnumber, float secondnumber );

}

First, createAbstract class

 

Public class operationfactory {

Public static operation getoperation (string quotaflag ){

Operation o = NULL;
Switch (quotaflag ){
Case "+": O = new addoptation ();
Case "-": O = new suboperationfactory ();
Case "*": O = new muloperation ();
Case "/": O = new divoperation ();
Default: break;

}
Return O;
}


}


Public class addoperation extends operation {

Public float getresult (float firstnumber, float secondnumber ){
Return firstnumber + secondnumber;
}
}


Public class suboperation extends operation {

Public float getresult (float firstnumber, float secondnumber ){
Return firstnumber-secondnumber;
}
}

Public class muloperation extends operation {

Public float getresult (float firstnumber, float secondnumber ){
Return firstnumber * secondnumber;
}
}

Public class divoperation extends operation {

Public float getresult (float firstnumber, float secondnumber ){
Return firstnumber/secondnumber;
}
}

Import java. util. collections;


Public class computer {


Public static void main (string [] ARGs ){
Running in = New Processing (system. In );
System. Out. println ("Enter the first number ");
Float firstnum = in. nextfloat ();
System. Out. println ("enter the second number ");

Float secondnum = in. nextfloat ();
System. Out. println ("Enter the operator ");
String countquato = in. Next ();
If ("+". Equals (countquato )){
System. Out. println ("Result:" + (firstnum + secondnum ));

} Else if ("-". Equals (countquato ));{
System. Out. println ("Result:" + (firstnum-secondnum ));

} Else if ("*". Equals (countquato ));{
System. Out. println ("Result:" + (firstnum * secondnum ));

} Else if ("/". Equals (countquato ));{
System. Out. println ("Result:" + (firstnum/secondnum ));


}
}
Private Static float count (float firstnum, float secondnum, string countquato ){
// Obtain the object through the factory class
Operation operation = operationfactory. getoperation (countquota );
Return operation. getresult (firstnum, secondnum );

}





}

}

 

 

 

 

 

A simple factory encapsulates the object creation process. You do not need to know the specific creation process. You only need to call the factory class to obtain the object.

This simple factory method uses switch-case to determine the object creation process. In actual use, the open-close principle is violated. Of course, in some cases, reflection calls can be used to make up for this deficiency.

 

 

 

Advantages/disadvantages of a simple factory: 

  • Advantage: the simple factory mode determines the specific class object to be created based on the information given by the outside world. Clearly differentiate their respective responsibilities and powers, which is conducive to the optimization of the entire software architecture.
  • Disadvantage: it is obvious that the factory class integrates the creation logic of all instances, which is easy to violate the graspr High Cohesion responsibility allocation principle.

 

 

2Factory methodDefine an interface for creating objectsLet the subclass decide which class to instantiate. The factory method delays the instantiation of a class to the subclass.
The factory method adds a factory layer based on a simple factory, and all factories are subclasses of this factory. The type of the generated object is determined by the subclass factory. Use the factory method to create the above addition, subtraction, multiplication, division object

 

// Define the interface of the primary store
Public interface ifractory {
Public operation generatoper ();

}
// Create a factory for each class
/**
* The Factory method generates a factory class for each object.
*/
Public class addoperationfactory implements ifractory {
Public operation generatoper (){
Return new addoperation ();
}
} Public class suboperationfactory implements ifractory {
Public operation generatoper (){
Return new suboperation ();
}
}
Public class muloperationfactory implements ifractory {
Public operation generatoper (){
Return new muloperation ();
}
}
Public classdivoperationfactory implements ifractory {
Public operation generatoper (){
Return new divoperation ();
}
}
// Client code
Ifractory fracation= new addoperationfactory ();
Operation operation = fracloud. generatloud ();
Operation. getresult (firstnum, secondnum );

 

 

The factory method delays class Instantiation to its subclass. Therefore, when using the factory method mode, the client needs to decide which factory class to instantiate. Determine whether the problem persists. That is to say, the factory method transfers a simple internal factory logic judgment to the client for running. The function you want to add is originally intended to change the factory class, but now you want to modify the client. However, in some cases, through the factory method, you only need to modify a line of instantiated code to switch system elements (such as switching data sources ). This is also very convenient.

Factory method. In the factory method mode, the core factory class is no longer responsible for the creation of all products, but rather the specific creation work is handed over to the Child class. This core class becomes an abstract factory role. It is only responsible for providing the interface that must be implemented by the specific factory subclass, and does not touch the details of which product class should be instantiated.

2.Definition: 

The factory method model is derived from the simple factory model and solves many problems of the simple factory model. First, the 'open-close policy' is fully implemented to achieve scalability. Secondly, a more complex hierarchy can be applied to scenarios where product results are complex.

3.Extension: 

In the introduction of the simple factory above, we handed over all the work of instantiating specific objects to the factory class (Field Service) dedicated to object creation, in this way, we can create the corresponding car (product) class after getting the director's command. However, the director of the cast is eccentric, and the instructions may change infinitely. In this way, there is a new problem. Once the Director sends a command that we did not expect, we must modify the source code. This is not very reasonable. The factory method is to solve such problems.

 

Advantages/disadvantages of the factory method: 

  • Advantages:
    • Subclass provides hooks. The base class provides default implementation for factory methods. Subclass can override the new implementation or inherit the implementation of the parent class. -- Adds an indirect layer to increase flexibility
    • Block product categories. The callers do not need to care about how the product class is implemented. They only need to care about the product interfaces. As long as the interfaces remain unchanged, the upper-layer modules in the system will not change.
    • A typical decoupling framework. The high-level module only needs to know the abstract class of the product. Other implementation classes do not need to be concerned. They comply with the dimit rule, the dependency inversion principle, and the lining replacement principle.
    • Polymorphism: the customer code can be unrelated to a specific application and applicable to any entity class.
  • Disadvantage: creator and the corresponding subclass must be used as the carrier of the factory method. If the application model does need creator and subclass, It is good; otherwise, a class hierarchy needs to be added. (However, this disadvantage seems a bit flawed)

Abstract Factory:

Provide a creationA seriesRelated interfaces of mutually dependent objects, without specifying their specific classes. Abstract Factory provides interfaces for object creation of different product families.
Use Cases: The system needs to switch between different product families
Code implementation:

 

Import muloperationfactory. idepartment;

// Use a factory for different product groups
Public class salserverfactory implements ifacfory {
Public iuser createuser (){
Return new sqiserveruser ();
}

} Public idepartment createdepartment (){

Return new sqiserverdepartment ();


}
Public class accessfactory implements ifacfory {
Public iuser createuser (){
Return new accessuser ();
Public idepartment createdepartment (){

Return new accessdepartment ();

}

Client:
Ifacfory facfory = new accessfactory ();
Iuser user = facfory. createuser ();
Idepartment Department = facfory. createdepartment ();
User. insert ();
User. getbyid ();
Department. insert ();
Department. getdepartmentbyid ();

 

 

 

 

 

 

 

FirstThe biggest benefit of the abstract factory isEasy to switch product seriesThe specific factory usually appears only once in the code. This makes it easy to change the specific factory of the application.

The second advantage is that it can separate the created object instance from the client. The client operates the instance through their abstract interface.

Abstract Factory is not easy to expand. If you need auto-increment functions or auto-increment products, you need to modify at least three classes, and the instantiated code is written to the program, in this way, the open-close principle cannot be avoided.
You can solve the above problems through the configuration file and reflection.

  1. 3. Abstract Factory mode is the most abstract and general factory mode in all forms. Abstract Factory mode refers to a factory mode used when multiple abstract roles exist. Abstract Factory mode provides an interface to the client to create product objects in multiple product families without specifying the specific product. According to the Rys replacement principle, any place that accepts the parent type should be able to accept the child type. Therefore, what the system actually needs is only some instances with the same type as those of abstract products, rather than the instances of these abstract products. In other words, it is an example of the concrete sub-classes of these abstract products. The factory class is responsible for creating instances of concrete subclasses of abstract products.

 

Abstract Factory: Definition

Provides an interface for creating a set of related or interdependent objects without specifying their specific classes.

Advantages/disadvantages of Abstract Factory: 

  • Advantages:
    • Abstract Factory mode isolates the production of specific classes so that customers do not need to know what is created.
    • When multiple objects in a product family are designed to work together, it ensures that the client always uses only objects in the same product family.
    • It is convenient to add a new factory or product family. You do not need to modify the existing system to comply with the "Open and Close principle ".
  • Disadvantages: adding a new product level structure is complex. You need to modify the abstract factory and all the specific factory classes, and the support for the "Open and Close principle" is skewed. (However, this disadvantage seems a bit flawed)

 

 

 


Three factory models with advanced features

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.