Introduction: Decoupling is a constant topic in the field of software design, in the process of software design, in order to minimize the coupling between various application components to improve its maintainability and reusability, there are many design principles and solutions. For example, interface-oriented programming, open-closed principle, relying on the inverted principle, and so on, and a series of design patterns. At the same time, because how to realize the decoupling involves a wide range, large to the Division and association of Components, small to object creation and reference, often make software developers confused. From the perspective of object creation and reference, this article introduces some common solutions and compares the differences, expecting readers to deepen their understanding of decoupling concepts from one side.
Application Scenarios
For the convenience of subsequent introductions, this paper assumes the application of a calculator. The initial design consists of the following parts:
Calculator Interface Class Calculatorui This class accepts user input expressions, performs some input validation, and passes the valid expression to a specific parser, which eventually returns the result to the user.
The parser interface, ExpressionEvaluator and its implementation class Expressionevaluatorimpl, it undertakes the actual computation work.
In this scenario, the Calculatorui class needs to hold a reference to the ExpressionEvaluator implementation to delegate its actual calculation at run time. The following article will focus on how to hold and initialize the ExpressionEvaluator implementation, and put forward a variety of solutions in turn.
Listing 1. Calculator Implementation mode one (new operator)
public class CalculatorUI {
private ExpressionEvaluator expressionEvaluator;
public CalculatorUI() {
expressionEvaluator = new ExpressionEvaluatorImpl();
}
public String evaluate(String expression) {
if (expression == null || expression.isEmpty()) {
throw new IllegalArgumentException("[" + expression + "]
is not a valid expression");
}
return expressionEvaluator.evaluate(expression);
}
}