8.4.3 C # Decision Tree
In the fifth chapter, we discuss the relationship between the differential union of F # and the class hierarchy in C #. In this example, we will use another kind of hierarchy to represent the nodes of the decision tree, and derive two additional classes to represent the two different cases (the final result and the query).
In a functional version, all the processing logic is implemented separately in the Testclienttree function. We use the visitor pattern (visitor pattern) in the object-oriented style (discussed in the seventh chapter), although this can be done, but this is not an authentic object-oriented solution. Here, we do not need to implement the function to handle the decision tree separately, so you can use more general object-oriented techniques, inheritance and virtual methods.
Listing 8.17 shows the simpler of the base class (decision) and two derived classes (Resultdecision), which represents the final result.
Listing 8.17 Object-oriented decision Trees (C #)
Abstract class Decision {
public abstract void Evaluate (clientclient); [1]
}
Class Resultdecision:decision {
public bool Result {get; set;}
public override void Evaluate (Clientclient) {[2]
Console.WriteLine ("Offer A LOAN: {0}", Result?) "YES": "NO");
}
}
This part of the code is fairly straightforward. The base class contains only a virtual method [1], which is implemented in the derived class, examines the customer, and outputs the result. The implementation in the class that represents the final result [2], outputs the results to the console.
The more important part is implementing the class that represents the query. The problem is that we need to provide different code for each specific query (check revenue, current work life, etc.). We can create a new derived class for each query, similar to the implementation of the Evaluate method, but the feeling is not a good solution because it involves code duplication. A better approach is to use the template method's design pattern.
8.4.3 C # Decision Tree