Follow the example to learn design patterns-static factory

Source: Internet
Author: User

The static factory design pattern is the creation design pattern.

Design intent: Instantiate the class objects we need, which can implement different functions or only implement one function!

Class Diagram Relationships:

Through the class diagram relationship we can see that the static factory is responsible for creating objects of the Operationfather class, so let's take a look at the instance code.

We want to implement a calculator, the function of the calculator temporarily has the addition, the subtraction function, may add the new function such as multiplication, division and so on at any time later. If we use a general approach, we can actually write a class to implement it.

Package com.factory.staticfactory;/** * @author Gaoxu * Practice the truth! */public class Operation {/** * @author Gaoxu * @param args */public static void main (string[] args) {//define variable//get incoming parameter//judgment pass Enter the calculation type if ("". Equals ("+")) {}else if ("". Equals ("-")) {}//Outputs the result of the calculation}}

We look at this implementation, the basic function is definitely implemented, but it seems that the extension is very poor, if we need to add a multiplication, that can only modify the IF statement to increase the condition, if constantly add new computing function, then this class can not be maintained, what kind of way to make the code beautiful, functional extension flexible, Is it easy to maintain?

Object-oriented programming can be implemented, first of all we need to encapsulate the implementation of the calculation, next we need to decouple the data acquisition settings and calculation of the logic, but also to consider the addition of features convenient and fast. The implementation of these points, we can also achieve code beautiful, functional expansion flexible, code maintenance convenience of several needs.

First we encapsulate the calculations, and we put the data into the parent class and put the calculations into different subclasses.

Package com.factory.staticfactory;/** * @author Gaoxu * Practice the truth! */public class Operationfather {double NumA = 0;double NumB = 0;public Double Getnuma () {return numA;} public void Setnuma (double numa) {This.numa = NumA;} Public double Getnumb () {return numB;} public void Setnumb (double numB) {this.numb = NumB;} Public double GetResult () {//TODO auto-generated method Stubreturn 0;}}

Package com.factory.staticfactory;/** * @author Gaoxu * Practice the truth! Addition */public class Operationadd extends operationfather{@Overridepublic double GetResult () {Double Result=0;result = NumA + Numb;return result;}}

Package com.factory.staticfactory;/** * @author Gaoxu * Practice the truth! Subtraction */public class Operationsub extends operationfather{@Overridepublic double GetResult () {Double result=0;result = NumA- Numb;return result;}}

we see above three classes, there is a parent class that is responsible for setting the data, and provides a method of calculation. The following two subclasses are an addition class, a subtraction class, each implementing their own business logic (overriding the method of the parent class), and the benefit is that each additional feature point will not be modified to the code of the other function.

What we are doing now is to create different functional products according to the user's needs, then we can use the static factory to see the implementation of the factory class.

Package com.factory.staticfactory;/** * @author Gaoxu * Practice the truth! */public class Staticfactory {public static operationfather Getoperationbytype (String type) {Operationfather operation = Null;if ("+". Equals (type)) {operation = new Operationadd ();} else if ("-". Equals (type)) {operation = new operationsub ();} return operation;}}

As you can see, we moved the judgment of what we did to the factory, we used the factory to encapsulate the process of creating objects, and the function of static methods was to create instance objects of different functions based on the parameters passed in. The creation of the object is also implemented, then see how to call it!

Package com.factory.staticfactory;/** * @author Gaoxu * Practice the truth! */public class Staticfactoryclient {public static void main (string[] para) {staticfactory factory = new Staticfactory (); String Operattype = "-"; Operationfather operate = Factory.getoperationbytype (Operattype); if (operate!=null) { Operate.setnuma (1); Operate.setnumb (5); System.out.println ("Two-phase" +operattype+ ", the result is as follows:" +operate.getresult ());} ELSE{SYSTEM.OUT.PRINTLN ("Operation class creation failed!") ");}}}

we can see that the client's code is also fairly concise, and it is clear what this class is going to do, without worrying about who is doing it. (This is done by the function to decide which object to dry)

From the above code we can see:

Client--factory class--Computing implementation class

The three-block relationship, each has its own business to do, the coupling is very low, the expansion of functionality, if the addition of new functions only need to implement a computational class, modify the factory static method of the judgment logic, thus we realized the code is concise, functional expansion flexible, maintenance convenience needs.

What scenarios are appropriate for creating with Factory mode:

1: Objects require a complex creation process that is too responsible for the client transcend.

2: Different objects can achieve different functions, need to have strong expansion requirements.

We give the creation of the object to the factory class and have the following advantages (relative to the implementation without using the factory):

1: The process of creating the product is encapsulated, through the necessary logic to realize the dynamic instantiation of the related class object, streamlining the client's code, removing the client and the specific product dependencies.

2: Can be effectively decoupled, the client and the specific implementation of the function of the class does not directly create a coupling relationship.

3: Can be a good reuse function, flexible add features, add products only need to modify the factory logic and add product implementation class.


Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

Follow the example to learn design patterns-static factory

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.