The beauty of Java [from rookie to master evolution] design pattern three __java

Source: Internet
Author: User
Tags int size

This chapter is the last lecture on design patterns, we will talk about the third design pattern-behavioral pattern, a total of 11 kinds: Policy mode, template method pattern, observer mode, iterative sub mode, responsibility chain mode, Command mode, Memo mode, state mode, visitor mode, mediator mode, interpreter mode. I've been writing about design patterns for a while, and I've finally written half of them, blogging is a time-consuming thing, because I have to be responsible for the reader, whether it is the picture or the code or presentation, all want to write clearly, so that readers understand, I think whether I or the reader, want to see the quality of the blog out, from my own , I will continue to go on, constantly updated, the source of power from the readers of the continuous support of friends, I will do my best to write every article. I hope you can continue to give comments and suggestions, together to create the perfect blog.

Learn technology, know how to share.

have any idea, please contact: Egg

email:xtfggef@gmail.com Weibo: Http://weibo.com/xtfggef

If reproduced, please indicate the source:http://blog.csdn.net/zhangerqing


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

The first class is implemented through the relationship between the parent class and the subclass. Category II: Between two classes. Class III: The state of the class. Class fourth: Through the middle class

13. Strategy Mode (strategy)

The policy pattern defines a series of algorithms and encapsulates each one so that they can be substituted for each other, and the changes in the algorithm do not affect the customers who use the algorithm. You need to design an interface that provides a unified approach to a series of implementation classes, implements the interface with multiple implementation classes, designs an abstract class (dispensable, belongs to a helper Class), and provides auxiliary functions, as follows:

In the diagram, ICalculator provides a method of consent,
Abstractcalculator is a helper class that provides an auxiliary method, followed by the implementation of each of the following classes:

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 {

	@Override public
	int Calculate (String EXP) {
		int arrayint[] = Split (exp, "\\+");
		return arrayint[0]+arrayint[1];
	}
public class minus extends Abstractcalculator implements ICalculator {

	@Override public
	int calculate (String exp {
		int arrayint[] = Split (exp, "-");
		return arrayint[0]-arrayint[1];
	}

public class Multiply extends Abstractcalculator implements ICalculator {

	@Override public
	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 decision power of the policy mode is in the user, the system itself provides the implementation of different algorithms, add or remove algorithms, and encapsulate various algorithms. Therefore, the strategy pattern is used in the algorithm decision system, the external user only needs to decide which algorithm to use.

14. Template Method Mode (Template methods)

Explain the template method pattern, which means: in an abstract class, there is a main method, and then a 1...N method, which can be abstract or practical, define a class, inherit the abstract class, override the abstract method, call the abstract class, implement the call to the subclass, and first look at the diagram:

is to define a Main method in the Abstractcalculator class Calculate,calculate () call spilt (), and so on, plus and minus inherit the Abstractcalculator class respectively, The invocation of the subclass is implemented by the invocation of the Abstractcalculator, as shown in the following example:

Public abstract class Abstractcalculator {
	
	/* Main method to implement calls to other methods in this class
	/public final int calculate (String exp,string opt) {
		int array[] = split (exp,opt);
		Return calculate (array[0],array[1]);
	
	/* The quilt class overrides the 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 {

	@Override public
	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 tracked the implementation of this applet: first, exp and "\\+" were used as parameters to invoke the Calculate (string,string) method in the Abstractcalculator class, in Calculate (string,string) To call the same kind of split (), and then call the Calculate (int, int) method, from this method into the subclass, after the return NUM1 + num2, the value returned to the Abstractcalculator class, assigned to result, printed out. It just validates the way we start.

15. Observer Mode (OBSERVER)

The next four patterns, including this one, are the relationships between classes and classes, not inheritance, and when you learn, you should remember to generalize and remember the first diagram of this article. Observer mode is well understood, similar to email subscriptions and RSS feeds, when we browse some blogs or wikis, we often see the RSS icon, which means that when you subscribe to the article, if there are updates, you will be notified in time. In fact, simply speaking: When an object changes, other objects that depend on that object will be notified, and with the change. Objects are a one-to-many relationship. Let's take a look at the diagram first:

I explain the role of these classes: The Mysubject class is our main object, Observer1 and Observer2 are objects that depend on Mysubject, and Mysubject and Observer1 inevitably change when Observer2 change. The Abstractsubject class defines a list of objects that you need to monitor to modify: Add or remove monitored objects and, when mysubject change, be responsible for notifying objects that exist in the list. Let's look at the implementation code:

A observer interface:

Public interface Observer {public
	void Update ();
}

Two implementation classes:

public class Observer1 implements Observer {

	@Override public
	Void Update () {
		System.out.println () Observer1 has received! ");
	}
public class Observer2 implements Observer {

	@Override public
	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 Notifyobservers ();
	
	/* Own operation *
	/public void operation ();
}
Public abstract class Abstractsubject implements Subject {

	private vector<observer> Vector = new Vector<obse Rver> ();
	@Override public
	void Add (Observer Observer) {
		vector.add (Observer);
	}

	@Override public
	void del (Observer Observer) {
		vector.remove (Observer);
	}

	@Override public
	void Notifyobservers () {
		enumeration<observer> Enumo = vector.elements ();
		while (Enumo.hasmoreelements ()) {
			enumo.nextelement (). Update ();}}
public class Mysubject extends Abstractsubject {

	@Override public
	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 received!
Observer2 has received!

These things, in fact, is not difficult, just some abstract, not easy to understand the whole, suggested that the reader: according to the diagram, new projects, write their own code (or refer to My Code), follow the general idea to go through it, so as to realize its thinking, easy to understand.

welcome readers at any time, discuss together, progress together.

have a problem, contact: Egg

email:xtfggef@gmail.com Weibo: Http://weibo.com/xtfggef

16, iterative sub-mode (iterator)

As the name implies, the iterator pattern is the sequential access to the objects in the aggregation, generally speaking, the collection is very common, if the collection class is more familiar with, understand this mode is very easy. This sentence contains two meanings: One is the object that needs to be traversed, that is, the aggregate object, and the other is the iterator object, which is used to traverse the clustered object. Let's look at the diagram:

This idea is exactly the same as we used to, mycollection defines a set of operations, Myiterator defines a series of iterative operations, and holds collection instances, let's look at the implementation code:

Two interfaces:

Public interface Collection {public
	
	iterator iterator ();
	
	/* Gets the Set element
	/public Object get (int i);
	
	/* Get the collection size *
	/public int size ();
}
Public interface Iterator {
	//forward-Move public
	Object Previous ();
	
	Move the public
	Object next () later;
	public boolean hasnext ();
	
	Gets the first element public
	Object one ();

Two implementations:

public class MyCollection implements Collection {public

	String string[] = {"A", "B", "C", "D", "E"};
	@Override Public
	iterator iterator () {return to
		new Myiterator (this);
	}

	@Override public
	Object get (int i) {return
		string[i];
	}

	@Override public
	int size () {return
		string.length;
	}
}
public class Myiterator implements iterator {

	private Collection Collection;
	private int pos =-1;
	
	Public Myiterator (Collection Collection) {
		this.collection = Collection;
	}
	
	@Override public
	Object Previous () {
		if (pos > 0) {
			pos--
		}
		Return Collection.get (POS);

	@Override public
	Object Next () {
		if (pos<collection.size ()-1) {
			pos++
		}
		Return Collection.get (POS);

	@Override Public
	Boolean hasnext () {
		if (pos<collection.size ()-1) {return
			true;
		} else{return
			false;
		}

	@Override Public
	Object A () {
		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 simulate the process of a collection class, it is not very cool. In fact, all the classes in the JDK are these basic things, plus some design patterns, plus some optimization put together, as long as we learn these things, master, we can also write their own collection class, or even the framework.

17. Responsibility chain mode (Chain of responsibility)
Next we're going to talk about the responsibility chain model, where there are multiple objects, each holding a reference to the next object, which creates a chain that requests to be passed on the chain until an object decides to process the request. But the issue is not clear to the end that the object will handle the request, so the responsibility chain model can be implemented, in the case of concealing the client, the system dynamic adjustment. First look at the diagram:

The Abstracthandler class provides get and set methods to facilitate Myhandle classes to set up and modify reference objects, and Myhandle classes are cores that generate a series of mutually held objects that 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;
	}

	@Override public
	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!

One thing to emphasize here is that the request on the link can be a chain, a tree, or a loop, the pattern itself does not constrain this, it needs to be implemented by ourselves, and at one time, the command allows only one object to be passed to another object, not to multiple objects.

18. Command mode

Command mode is well understood, for example, the commander ordered the soldiers to do something, from the point of view of the whole thing, the commander's role is to send a password, the password passed, reached the soldiers ear, the soldiers to carry out. The process is good, the three mutual decoupling, no one need to rely on others, just to do their own thing on the line, the commander is the result, not to pay attention to exactly how the soldiers to achieve. Let's look at the diagram:

Invoker is the caller (commander), receiver is the callee (soldier), MyCommand is the command, implements the command interface, holds the receiving object, and looks at the implementation code:

Public interface Command {public
	void exe ();
}
public class MyCommand implements Command {

	private Receiver Receiver;
	
	Public mycommand (Receiver Receiver) {
		this.receiver = Receiver;
	}

	@Override public
	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 very well understood, the purpose of the command mode is to achieve the command of the creator and performer decoupling between the implementation of the request and implementation of the separation, familiar with struts should know, struts is actually a request and rendering separation of technology, which necessarily involves the idea of command mode.

This article is here for the time being, because considering the future blog will be constantly updated, constantly adding new content, so the current length is not easy too long so that everyone can read, so the next one in another. Please pay attention.

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.