When we have mastered the Java syntax, when we understand the object-oriented encapsulation, inheritance, polymorphism and other features, when we can use swing, Servlet, JSP technology to build desktop and Web applications, it does not mean that we can write object-oriented programs. It does not mean that we can achieve code reuse and flexible maintenance. It does not mean that we can achieve code reuse based on maintenance and expansion. A knife can make your enemy stand out from the invisible and famous, or just a sharp blade to make you cut vegetables calmly. Java is the tool. Its power depends on how you use it. When we get stuck with endless repetitive code, and when we are faced with a full-blown maintenance nightmare, you should think of the "Design Pattern" Action secret. The essence of object-oriented seems plain. In fact, it can be successful only after hard practices. The implicit experience of building an OO system was collected by our predecessors and named "Design Pattern. We should carry it at the beginning of the encoding action. Next, let's start with the "four-person group" and use Chinese characters and actual cases to understand the new pattern of our code:
One of the design patterns: policy patterns
1. Schema Definition
Extract and encapsulate the changed content so that it can be easily modified or expanded in the future without affecting other parts that do not need to be changed;
2. Origin
When code maintenance is involved and inheritance is used for reuse purposes, the outcome is not perfect. Modifications to the parent class will affect the child type. The method added to the superclass will cause the child type to have this method, and even the child types that do not have this method cannot be exempted.
Example: A duck type: (the example is from Head first. Design Mode)
Public abstract class duck {// all ducks are called and swimming, so the code public void quack () {system. out. println ("quack");} public void swim () {system. out. println ("all ducks float, even decoys. ");} // because each duck looks different, the method in the parent class is abstract and completed by the Child type. Public abstract void display ();} public class mallardduck extends duck {// the appearance of the wild duck is displayed as the green head public void display () {system. out. println ("green head. ") ;}} public class redheadduck extends duck {// red head duck is displayed as red head public void display () {system. out. println ("red head. ") ;}} public class rubberduck extends duck {// rubber duck call refers to squat, So rewrite the parent class to rewrite the behavior public void quack () {system. out. println ("Squeak");} // the Rubber Duck is displayed as a yellow head public void display () {system. out. println ("yellow head. ");}}
The above code is initially implemented very well. Now, if we add the fly () method to duck. Java, this method is available in the Child type, so we can see the Flying rubber duck. Have you ever seen it? Of course, we can rewrite this method with null in the subclass to solve the impact of this method on the child type. But what about adding other methods to the parent class?
Providing behavior in the parent class causes the following Disadvantages:
A. The code is repeated among multiple child classes;
B. The behavior during running is not easy to change;
C. Changes will trigger the whole body, resulting in unnecessary changes to some subtypes;
Okay, just now the duck example. You may think of using interfaces to define flying behaviors and calling behaviors as interfaces, and then let the various subtypes of duck implement these interfaces. The code is similar:
Public abstract class duck {// separates the changed behavior fly () and quake () from the duck class to define an interface, and automatically implements public void swim () in the required subclass () {system. out. println ("all ducks float, even decoys. ") ;}public abstract void display () ;}// the changed fly () behavior definition interface public interface flybehavior {void fly ();} // The public interface quackbehavior {void quack ();} // The interface flybehavior, quackbehaviorpublic class mallardduck extends duck implements flybehavior, quackbehavior {public void display () {system. out. println ("green head. ");} public void fly () {system. out. println ("fly. ");} public void quack () {system. out. println ("quack. ") ;}}// the red-headed duck can fly and call it. Therefore, the interface flybehavior, quackbehaviorpublic class redheadduck extends duck implements flybehavior, quackbehavior {public void display () {system. out. println ("red head. ");} public void fly () {system. out. println ("fly. ");} public void quack () {system. out. println ("quack. ") ;}} // the Rubber Duck will not fly, but it will scream, so it only implements the interface quackbehaviorpublic class rubberduck extends duck implements quackbehavior {// The rubber duck calls public void quack () {system. out. println ("Squeak");} // the Rubber Duck is displayed as a yellow head public void display () {system. out. println ("yellow head. ");}}
Although the above code solves some problems, it allows the child type to selectively provide some behaviors (for example, the fly () method will not appear in the Rubber Duck ). but we can also see that the wild duck mallardduck. java and red-headed duck redheadduck. some Java code with the same behavior cannot be reused. To a large extent, this is from one fire pit to another.
After a program, let's jump out of the details and pay attention to some common problems. No matter what language or application is used, the constant truth that persists in software development is that the need remains changing. No matter how well the software is designed at the beginning, it will always need to grow and change after a period of time, otherwise the software will die.
We know that inheritance can realize code reuse to some extent, but the behavior of the parent class (such as duck) is constantly changing in the Child type, it is inappropriate to make all child types have these behaviors. We can define these behaviors as interfaces to implement various sub-types of duck, but interfaces do not have implementation code, so the implementation interfaces cannot achieve code reuse. This means that when we need to modify an action, we must track down and modify it in every class that defines this behavior. If we do not care, new errors will occur.
Design Principle: Separate the changes in the application and do not mix them with the code that does not need to be changed. In this way, the casual consequences of code changes become less, and the system becomes more flexible.
Based on the above design principles, we review the previous duck code.
1) Separate the changed content and unchanged content
The behavior fly () and quack () in the duck class, each subtype may have its own unique performance, which is the so-called change content.
The behavior swim () in the duck class has the same performance for each subtype. This is the so-called unchanged content.
We split the changed content from the duck () class and separately defined the interface and a series of implementation types. Interfaces that define changed content can be used to strip changed content and unchanged content. The implementation type can reuse the changed content. These implementation classes are not child types of duck. Java, but a special set of implementation classes called "behavior classes ". The interface is implemented by the behavior class instead of the Child type of duck. java. In this way, we can ensure that the changed behavior is independent of the unchanged content. So we have:
Changed content:
// The changed fly () action definition interface public interface flybehavior {void fly ();} // The changed fly () public class flywithwings implements flybehavior {public void fly () {system. out. println ("I'm flying. ") ;}}// the second implementation class of the changed fly () behavior public class flynoway implements flybehavior {public void fly () {system. out. println ("I can't fly. ");}}
// The public interface quackbehavior {void quack () formed by the changed quack () behavior definition;} // The changed quack () one of the behavior implementation classes is public class quack implements quackbehavior {public void quack () {system. out. println ("quack") ;}// change the quack () behavior implementation Class II public class squeak implements quackbehavior {public void quack () {system. out. println ("squeak. ") ;}} // variable quack () behavior implementation Class 3 Public class mutequack implements quackbehavior {public void quack () {system. out. println ("<slience> ");}}
Through the above design, fly () behavior and quack () behavior have nothing to do with duck. Java and can be fully reused. In addition, we can easily add new behaviors without affecting the existing behaviors or duck. java. However, you may have a question: isn't the behavior in object orientation reflected as a method? Why is it defined to form a class (for example, Squeak. Java )? In OO, "things" represented by classes generally have both statuses (instance variables) and methods. In this example, "things" happens to be an action. Both behaviors and attributes and methods are available. For example, flight behaviors also require some attributes to record the flight status, such as the flight height and speed.
2) Integrate the changed content and unchanged content
Public abstract class duck {// declare the behavior class as the interface type, reducing the dependency on the behavior Implementation type flybehavior; quackbehavior; Public void javasmfly () {// The Fly () action is not handled by the user, but is dragged to the flybehavior object referenced by flybehavior. fly ();} public void initialize mquack () {quackbehavior. quack ();} public void swim () {system. out. println ("all ducks float, even decoys. ");} public abstract void display ();}
Duck. Java does not care about fly () and quack (). These details are handled by specific behavior classes.
public class MallardDuck extends Duck{ public MallardDuck() { flyBehavior=new FlyWithWings(); quackBehavior=new Quack(); } public void display() { System.out.println("Green head."); }}
public class DuckTest { public static void main(String[] args) { Duck duck=new MallardDuck(); duck.performFly(); duck.performQuack(); }}
In the constructor of the duck. Java sub-type mallardduck. Java, the behavior type is directly instantiated and the specific behavior type is specified during compilation. Of course, we can:
1) We can further solve the problem through the factory mode or other mode (refer to the subsequent mode );
2) or dynamically change the behavior at runtime.
3) dynamically set Behavior
Add the setter method for setting the behavior type in the parent class duck. Java to accept the parameter input of the behavior type object. To reduce the coupling, the behavior parameter is declared as the interface type. In this way, you can change the behavior either at runtime or by calling these two methods.
Public abstract class duck {// Add the following two methods to duck. java. Public void setflybehavior (flybehavior) {This. flybehavior = flybehavior;} public void setquackbehavior (quackbehavior) {This. quackbehavior = quackbehavior;} // the same as other methods, omitting ...}
public class DuckTest { public static void main(String[] args) { Duck duck=new MallardDuck(); duck.performFly(); duck.performQuack(); duck.setFlyBehavior(new FlyNoWay()); duck.performFly(); }}
If we want to add Rocket-Assisted flight behavior, we only need to create the implementation type of the flybehavior. Java interface. The child type can be dynamically changed by calling the setquackbehavior (...) method. So far, adding new behaviors in duck. Java will no longer cause code loops.
This is the time to sum up. Let's float out of the Code and make a duck swimming freely on the water:
3. Solution
Mallardduck inherits the duck abstract class;-> unchanged content
Flywithwings implements the flybehavior interface;-> changed content, behavior, or Algorithm
Provides the setter method in duck. Java to assemble the relationship.-> dynamically sets the behavior.
The above is the three-step implementation of the Policy mode. Next, let's look at the essence through the steps:
1) At the beginning, we realized the reuse of behavior through inheritance, resulting in code maintenance problems. -> Inheritance, is
2) then, we split the behavior into an instance variable of a separate type and declared as unchanged content and combined it with->, has
Setter method to assemble the relationship;
Inheritance can achieve static code reuse; combination can achieve flexible code maintenance; use combination instead of inheritance can make the Code better adapt to the demand changes after software development.
The essence of policy mode: less inheritance and more combination