Design Patterns-11 behavioral patterns

Source: Internet
Author: User
Tags int size


Reprint: http://blog.csdn.net/u013142781/article/details/50825301


There are 23 kinds of Java Classic design patterns, which are divided into three categories: the creation mode (5 kinds), the structure pattern (7 kinds) and the behavior pattern (11 kinds).


Behavioral patterns are subdivided into 11 types: Policy mode, template method pattern, observer mode, iterative sub mode, responsibility chain mode, Command mode, Memo mode, State mode, visitor pattern, mediator mode, interpreter mode.

Next, the 11 behavioral patterns are described individually. first, the strategy model

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 (optional, belongs to the auxiliary class, depending on whether the actual requirements are added), and provides an auxiliary function.

First Unified Interface:

Package com.model.behaviour;

Public interface ICalculator {
public int Calculate (String exp);
}


Auxiliary class:

Package com.model.behaviour;

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:

Package com.model.behaviour;

public class Plus extends Abstractcalculator implements ICalculator {

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


Package com.model.behaviour;

public class minus extends Abstractcalculator implements ICalculator {

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

}


Package com.model.behaviour;

public class Multiply extends Abstractcalculator implements ICalculator {

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


Test class:

Package com.model.behaviour;

public class Strategytest {

public static void Main (string[] args) {
String exp = "8-2";
ICalculator cal = new Minus ();
int result = Cal.calculate (exp);
SYSTEM.OUT.PRINTLN (exp + "=" + result);
}
}


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. mode of template method

Explain the template method pattern, 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, and implement the invocation of the subclass by invoking the abstract class.

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:

Package com.model.behaviour;

Public abstract class Abstractcalculator {

/* Main method, implement the call to 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 rewrite 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;
}
}


Package com.model.behaviour;

public class Plus extends Abstractcalculator {

@Override
public int calculate (int num1,int num2) {
return NUM1 + num2;
}
}


Package com.model.behaviour;

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);
}
}


III. Observer Model

The next four patterns, including this one, are the relationships between classes and classes and do not involve inheritance.

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.

Package com.model.behaviour;

Public interface Observer {
public void update ();
}


Package com.model.behaviour;

public class Observer1 implements Observer {

@Override
public void Update () {
System.out.println ("Observer1 has received!");
}
}


Package com.model.behaviour;

public class Observer2 implements Observer {

@Override
public void Update () {
System.out.println ("Observer2 has received!");
}

}


Package com.model.behaviour;

Public interface Subject {

* * To increase the observer/
public void Add (Observer Observer);

* * Delete observer/
public void del (Observer Observer);

/* Notify all observers * *
public void notifyobservers ();

/* Own Operation * *
public void operation ();
}


Package com.model.behaviour;

Import Java.util.enumeration;import java.util.Vector;

Public abstract class Abstractsubject implements Subject {

Private vector<observer> Vector = new vector<observer> ();
@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 ();
}
}
}


Package com.model.behaviour;

public class Mysubject extends Abstractsubject {

@Override
public void operation () {
System.out.println ("Update self!");
Notifyobservers ();
}

}


Package com.model.behaviour;

public class Observertest {

public static void Main (string[] args) {
Subject sub = new Mysubject ();
Sub.add (New Observer1 ());
Sub.add (New Observer2 ());

Sub.operation ();
}

}

Run Result:

Update self!
Observer1 has received!
Observer2 has received!


Perhaps after the example is still more abstract, and then read the text description and code examples one or two times, and then combine the work to see which scenes can use this pattern to deepen understanding. Iv. Iterative sub-mode

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.

Take a look at the code example:

Package com.model.behaviour;

Public interface Collection {

Public iterator iterator ();

/* Get the SET elements * *
Public Object get (int i);

/* Get the SET size * *
public int size ();
}


Package com.model.behaviour;

Public interface Iterator {
Move forward
Public Object Previous ();

Move back
Public Object next ();

public boolean hasnext ();

Get the first element
Public Object A ();
}


Package com.model.behaviour;

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;
}
}


Package com.model.behaviour;

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);
}

}


Package com.model.behaviour;

public class Test {

public static void Main (string[] args) {
Collection Collection = new mycollection ();
Iterator it = (iterator) collection.iterator ();
while (It.hasnext ()) {
System.out.println (It.next ());
}
}
}



Output results:

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. Five, the responsibility chain model

Responsibility chain mode, there are multiple objects, each object holds 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.

Package com.model.behaviour;

Public interface Handler {
public void operator ();
}


Package com.model.behaviour;

Public abstract class Abstracthandler {

Private Handler Handler;

Public Handler GetHandler () {
return handler;
}

public void SetHandler (Handler Handler) {
This.handler = handler;
}

}


Package com.model.behaviour;

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 ();
}
}
}


Package com.model.behaviour;

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 ();
}
}




Run Result:

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. Six, 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 role of the Commander is to export

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.