The beauty of Java [from cainiao to master Evolution] Design Pattern 3

Source: Internet
Author: User

This chapter is the last lecture on design patterns. It will introduce the third design patterns-behavioral patterns, 11 in total: rule mode, template method mode, observer mode, iteration sub-mode, responsibility chain mode, command mode, memorandum mode, state mode, visitor mode, intermediary mode, interpreter mode. I have been writing about the design pattern during this time, and I have finally written it in half. It is very time-consuming to write a blog post, because I am responsible for the reader, whether it is a diagram, code, or expression, I hope to write it clearly as much as possible so that readers can understand it. I think both me and readers hope to see high-quality blog posts. Starting from myself, I will keep on updating, the source motivation comes from the constant support of readers and friends. I will do my best to write every article! I hope you will continue to give comments and suggestions to build a perfect blog!

Learn Technology and learn how to share it!

If you have any idea, please contact: Egg

Email: xtfggef@gmail.com Weibo: http://weibo.com/xtfggef

If any reprint is available, please describe the source:Http://blog.csdn.net/zhangerqing


Let's take a look at the relationship between the patterns in 11:

The first type is implemented through the relationship between the parent class and the Child class. Category 2: between two classes. Category 3: the status of the class. Category 4: Intermediate Class

13. Strategy)

Policy mode defines a series of algorithms and encapsulates each algorithm so that they can replace each other, and the algorithm changes will not affect the customers who use the algorithm. You need to design an interface to provide a uniform method for a series of implementation classes. Multiple implementation classes implement this interface, design an abstract class (optional and optional), and provide auxiliary functions. The relationship diagram is as follows:

In the figure, icalculator provides the consent method,
Abstractcalculator is a helper class that provides helper methods. Next, implement each class in sequence:

First, unified interface:

public interface ICalculator {public int calculate(String exp);}

Auxiliary class:

public abstract class AbstractCalculator {public int[] split(String exp,String opt){String array[] = exp.split(opt);int arrayInt[] = new int[2];arrayInt[0] = Integer.parseInt(array[0]);arrayInt[1] = Integer.parseInt(array[1]);return arrayInt;}}

Three implementation classes:

public class Plus extends AbstractCalculator implements ICalculator {@Overridepublic int calculate(String exp) {int arrayInt[] = split(exp,"\\+");return arrayInt[0]+arrayInt[1];}}
public class Minus extends AbstractCalculator implements ICalculator {@Overridepublic int calculate(String exp) {int arrayInt[] = split(exp,"-");return arrayInt[0]-arrayInt[1];}}
public class Multiply extends AbstractCalculator implements ICalculator {@Overridepublic int calculate(String exp) {int arrayInt[] = split(exp,"\\*");return arrayInt[0]*arrayInt[1];}}

Simple test class:

public class StrategyTest {public static void main(String[] args) {String exp = "2+8";ICalculator cal = new Plus();int result = cal.calculate(exp);System.out.println(result);}}

Output: 10

The policy mode is determined by the user. The system itself provides implementation of different algorithms, adds or deletes algorithms, and encapsulates various algorithms. Therefore, policy modes are generally used in algorithm decision making systems. external users only need to decide which algorithm to use.

14. Template Method)

The template method mode refers to a main method in an abstract class and defines 1... n methods can be abstract or actual methods. Define a class, inherit the abstract class, override the abstract method, and call the abstract class to call the subclass, first look at the relationship diagram:

Is to define a main method calculate in the abstractcalculator class, calculate () calls spilt (), and so on. plus and minus inherit the abstractcalculator class, and call the abstractcalculator class to realize the subclass, see the following example:

Public abstract class abstractcalculator {/* main method to call other methods of this class */public final int calculate (string exp, string OPT) {int array [] = Split (exp, OPT); return calculate (array [0], array [1]);}/* quilt class override method */Abstract Public int calculate (INT num1, int num2 ); public int [] Split (string exp, string OPT) {String Array [] = exp. split (OPT); int arrayint [] = new int [2]; arrayint [0] = integer. parseint (array [0]); arrayint [1] = integer. parseint (array [1]); Return arrayint ;}}
public class Plus extends AbstractCalculator {@Overridepublic int calculate(int num1,int num2) {return num1 + num2;}}

Test class:

public class StrategyTest {public static void main(String[] args) {String exp = "8+8";AbstractCalculator cal = new Plus();int result = cal.calculate(exp, "\\+");System.out.println(result);}}

I keep track of the execution process of this applet: first, set exp and "\ +" as parameters and call the calculate (string, string) method in the abstractcalculator class. In the calculate (string, string), and then call the calculate (INT, INT) method, from this method into the subclass, after the return num1 + num2 is executed, return the value to the abstractcalculator class, assign it to the result, and print it out. It just verifies our initial thinking.

15. Observer mode (observer)

The next four models, including this mode, are the relationships between classes and classes, which do not involve inheritance. Remember to sum up when learning. Remember the figure at the beginning of this article. The observer mode is easy to understand, similar to email subscription and RSS subscription. When we browse some blogs or wikis, we often see RSS icons. This means that when you subscribe to this article, you will be notified of any updates later. In fact, simply put, when an object changes, other objects dependent on this object will be notified and will change accordingly! An object is a one-to-multiple relationship. Let's take a look at the relationship diagram:

I will explain the role of these classes: mysubject class is our main object, observer1 and observer2 are dependent on mysubject objects. When mysubject changes, observer1 and observer2 will inevitably change. The abstractsubject class defines the list of objects to be monitored. You can modify the list to add or delete Monitored Objects. When mysubject changes, it notifies the objects in the list. The implementation code is as follows:

An observer interface:

public interface Observer {public void update();}

Two implementation classes:

public class Observer1 implements Observer {@Overridepublic void update() {System.out.println("observer1 has received!");}}
public class Observer2 implements Observer {@Overridepublic void update() {System.out.println("observer2 has received!");}}

Subject interface and implementation class:

Public interface subject {/* Add Observer */Public void add (Observer observer);/* Delete Observer */Public void del (Observer observer ); /* notify all Observers */Public void policyobservers ();/* its own operations */Public void operation ();}
public abstract class AbstractSubject implements Subject {private Vector<Observer> vector = new Vector<Observer>();@Overridepublic void add(Observer observer) {vector.add(observer);}@Overridepublic void del(Observer observer) {vector.remove(observer);}@Overridepublic void notifyObservers() {Enumeration<Observer> enumo = vector.elements();while(enumo.hasMoreElements()){enumo.nextElement().update();}}}
public class MySubject extends AbstractSubject {@Overridepublic void operation() {System.out.println("update self!");notifyObservers();}}

Test class:

public class ObserverTest {public static void main(String[] args) {Subject sub = new MySubject();sub.add(new Observer1());sub.add(new Observer2());sub.operation();}}

Output:

Update self!
Observer1 has already ed!
Observer2 has already ed!

These things are not difficult, but abstract and not easy to understand. We recommend that you:Create a project based on the relationship diagram and write your own code (or refer to my code ),FollowThe general idea can be understood and easy to understand!

Readers are welcome to make corrections, discuss and make progress at any time!

If you have any questions, contact egg.

Email: xtfggef@gmail.com Weibo: http://weibo.com/xtfggef

16. Iteration submodel (iterator)

As the name suggests, the iterator mode is used to access objects in the aggregation sequentially. Generally, collection is very common. If you are familiar with collection classes, it is very easy to understand this mode. This sentence contains two meanings: first, the object to be traversed, that is, the clustering object, and second, the iterator object, which is used to traverse and access the clustering object. Let's look at the relationship diagram:

 

This idea is exactly the same as what we usually use. mycollection defines some operations of the set. myiterator defines a series of iterative operations and holds collection instances. Let's take a look at the implementation code:

Two interfaces:

Public Interface collection {public iterator ();/* Get Set element */public object get (int I);/* Get Set size */Public int size ();}
Public interface iterator {// forward public object previous (); // move public object next (); Public Boolean hasnext (); // obtain the first element public object first ();}

Two implementations:

public class MyCollection implements Collection {public String string[] = {"A","B","C","D","E"};@Overridepublic Iterator iterator() {return new MyIterator(this);}@Overridepublic Object get(int i) {return string[i];}@Overridepublic int size() {return string.length;}}
public class MyIterator implements Iterator {private Collection collection;private int pos = -1;public MyIterator(Collection collection){this.collection = collection;}@Overridepublic Object previous() {if(pos > 0){pos--;}return collection.get(pos);}@Overridepublic Object next() {if(pos<collection.size()-1){pos++;}return collection.get(pos);}@Overridepublic boolean hasNext() {if(pos<collection.size()-1){return true;}else{return false;}}@Overridepublic Object first() {pos = 0;return collection.get(pos);}}

Test class:

public class Test {public static void main(String[] args) {Collection collection = new MyCollection();Iterator it = collection.iterator();while(it.hasNext()){System.out.println(it.next());}}}

Output: A B C D E

Here we seem to have simulated the process of a collection class. Is it nice? In fact, all the classes in JDK are also these basic things. We can add some design patterns and some optimizations together. As long as we have learned and mastered these things, we can also write our own collection classes and even frameworks!

17. chain of responsibility)
Next, we will talk about the responsibility chain model. There are multiple objects, each of which holds a reference to the next object. In this way, a chain is formed and requests are transmitted on this chain, until an object decides to process the request. However, the sender does not know whether the final object will process the request. Therefore, the responsible chain mode can be implemented to dynamically adjust the system when the client is concealed. First look at the relationship diagram:

The abstracthandler class provides get and set methods to facilitate the myhandle class to set and modify reference objects. The myhandle class is the core. after instantiation, a series of mutually held objects are generated to form a chain.

public interface Handler {public void operator();}
public abstract class AbstractHandler {private Handler handler;public Handler getHandler() {return handler;}public void setHandler(Handler handler) {this.handler = handler;}}
public class MyHandler extends AbstractHandler implements Handler {private String name;public MyHandler(String name) {this.name = name;}@Overridepublic void operator() {System.out.println(name+"deal!");if(getHandler()!=null){getHandler().operator();}}}
public class Test {public static void main(String[] args) {MyHandler h1 = new MyHandler("h1");MyHandler h2 = new MyHandler("h2");MyHandler h3 = new MyHandler("h3");h1.setHandler(h2);h2.setHandler(h3);h1.operator();}}

Output:

H1deal!
H2deal!
H3deal!

Here, we emphasize that the request on the link can be a chain, a tree, or a ring, and the pattern itself does not constrain this. We need to implement it ourselves. At the same time, at one time point, a command can only pass one object to another, rather than multiple objects.

18. Command)

The command mode is easy to understand. For example, the commander ordered soldiers to do things. From the perspective of the whole thing, the role of the commander was to send a password and pass the password, it is passed to the ears of the soldiers and executed by the soldiers. This process is good. The three are decoupled from each other. No one needs to depend on others. You only need to do your own thing. What the commander wants is the result, they will not focus on how soldiers are actually implemented. Let's look at the relationship diagram:

Invoker is the caller (the Commander), the consumer er is the caller (the soldier), and The mycommand is the command. It implements the command interface and holds the receiving object. See the implementation code:

public interface Command {public void exe();}
public class MyCommand implements Command {private Receiver receiver;public MyCommand(Receiver receiver) {this.receiver = receiver;}@Overridepublic void exe() {receiver.action();}}
public class Receiver {public void action(){System.out.println("command received!");}}
public class Invoker {private Command command;public Invoker(Command command) {this.command = command;}public void action(){command.exe();}}
public class Test {public static void main(String[] args) {Receiver receiver = new Receiver();Command cmd = new MyCommand(receiver);Invoker invoker = new Invoker(cmd);invoker.action();}}

Output: Command received!

This is understandable. The purpose of the command mode is to decouple the sender and executor of the command to separate requests and executions. Students familiar with Struts should know that, struts is actually a technology that separates requests from presentation, which must involve the idea of the command mode!

This article is here for the time being, because in the future blog posts will be constantly updated and new content will be constantly added, so the current length is not too long for everyone to read, so I will put it in another article. Stay tuned!

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.