The behavioral pattern of Java Classic 23 design patterns (II.)

Source: Internet
Author: User
Tags int size

In this paper, we introduce the interpreter pattern, the iterator pattern and the mediator pattern in the behavioral pattern.

first, the interpreter mode interpret

Given a language, define a representation of its grammar and define an interpreter that interprets the sentences in the language using that representation.

1.AbstractExpression (abstract expression) declares an abstract interpretation operation that is shared by all nodes in the abstract syntax tree.

Public abstract class Expression {
abstract void interpret (Context ctx);
}

The 2.Expression implements an interpreted operation that is associated with Terminator in the grammar.

public class Advanceexpression extends Expression {    void interpret (Context ctx) {        System.out.println ("This is an advanced parser!");    }} public class SimpleExpression extends Expression {    void interpret (Context ctx) {        System.out.println ("This is a normal parser!");    }}

3.Context (context) includes some global information outside of the interpreter.

public class Context {    private String content;        Private list List = new ArrayList ();        public void SetContent (String content) {        this.content = content;    }        Pu*lic String getcontent () {        return this.content;    }        public void Add (Expression eps) {        list.add (eps);    }        Public List getList () {        return list;    }}

Test code:

public class Test {


public static void Main (string[] args) {
Context CTX = new context ();
Ctx.add (New SimpleExpression ());
Ctx.add (New Advanceexpression ());
Ctx.add (New SimpleExpression ());

For (Expression eps:ctx.getList ()) {
Eps.interpret (CTX);
}
}
}
Result
This is an ordinary parser!
This is the Advanced parser!
This is an ordinary parser!

Applicability:
When a language needs to be interpreted to run, and you can represent a sentence in that language as an abstract syntax tree, you can make
Use the Interpreter mode. This mode works best when there are * conditions:
1. The grammar is simple for complex grammars, and the grammatical hierarchy becomes large and cannot be managed.


2. Efficiency is not a key issue the most efficient interpreters are usually not implemented by directly interpreting the parse tree, but rather first converting them to a form.


This sample is still not typical enough to refer to the example in link http://blog.csdn.net/feier7501/article/details/8604151.

Second, the iterator mode Interator

Provides a way to access individual elements in a container object. Without leaking the inner details of the object. Claims to be the most used mode in Java.

The 1.Iterator iterator defines an interface for visiting and traversing elements.

Public interface Iterator {


Object next ();

void First ();

void last ();

Boolean hasnext ();
}

The 2.ConcreteIterator detailed iterator implements the iterator interface. Tracks the current position on the aggregation pass-through duration.

public class Iteratorimpl implements Iterator {    private list list;        private int index;        Public Ite*atorimpl (List list* {        index = 0;        this.list = list;    }        public void First () {        index = 0;    }    public void Last () {        index = list.getsize ();    }    Public Object Next () {        Object obj = List.get (index);        index++;        Ret*rn obj;    }    public Boolean Hasnext () {        return index < List.getsize ();}    }

The 3.Aggregate aggregation defines the interface that creates the corresponding iterator object.

Public interface List {

Iterator Iterator ();

Object get (int index);

int GetSize ();

void Add (Object obj);
}

The 4.ConcreteAggregate detailed aggregation implementation creates an interface for the corresponding iterator that returns an appropriate instance of Concreteiterator.

public class Listimpl implements list {    private object[] list;        private int index;        private int size;        Public Listimpl () {        index = 0;        size = 0;        List = new object[100];    }        Public Iterator Iterator () {        return to new Iteratorimpl (this);    }        Public o*ject get (int index) {        return list[index];    }        public int GetSize () {        return this.size;    }        public void Add (Object obj) {        list[index++] = obj;        size++;}    }
Test Code:

public class Test {public    stati* void Main (string[] arg*) {        list list = new Listimpl ();        List.add ("a");        List.add ("B");        List.add ("C");        The first iteration of        Iterator it = List.iterator ();        while (*t.ha*next ()) {            s*stem.out.println (It.next ());        }                Syst*m.out.println ("=====");        Another iterative way for        (int i = 0; i < list.getsize (); i++) {            System.out.println (List.get (i))}        }}    

Applicability:

1. Access the content of an aggregated object without exposing its internal representation.
2. Support for multiple traversal of aggregation objects.


3. Provide a unified interface for traversing different aggregation structures (that is, support for polymorphic iterations).

Iterator patterns are not often used. Java itself has provided the perfect support, many other visible links: http://blog.csdn.net/chenhuade85/article/details/8146992

Third, the intermediary mode

Encapsulates a series of object interactions with a mediation object. Intermediaries make it unnecessary for objects to explicitly cross-reference each other. This allows it to be loosely coupled and can independently change the interaction between them.

1.Mediator
A mediator defines an interface for communicating with each colleague (colleague) object.


Public abstract class Mediator {


public abstract void Notice (String content);
}

2.ConcreteMediator detailed intermediaries achieve collaborative behavior by coordinating their colleagues ' objects. Understand and maintain all of its colleagues.


Public *lass Concretemediator e*tends Mediator {


Private Colleaguea CA;

Pri*ate Colleagueb CB;

Public Concretemediator () {
CA = new Colleaguea ();
cb = new Col*eagueb ();
}

public void No*ice (String content) {
if (Co*tent.equals ("Boss")) {
The Boss is here, notify staff A.
Ca*action ();
}
if (Content.equals ("client")) {
The customer came, * know the front desk b
Cb.action ();
}
}
}


3.Colleagueclass each colleague class knows its mediator object.

Each colleague object communicates with its mediator when it needs to communicate with other colleagues.

Public class Colleaguea extends colleague {



public void action () {
System.out.println ("Hard work of ordinary employees");
}
}


Public class Colleagueb extends colleague {


public void action () {
System.out.println ("Attention at the front desk!");
}
}

Test code:
public class Test {


public static void Main (string[] args) {
Mediator Med = new Concretemediator ();
The boss is here.
Med.notice ("Boss");

The client is here.
Med.notice ("Client");
}
}
Result


Ordinary employees work hard
Front desk attention!

Applicability:

1. A group of objects communicates in a well-defined but complex way.

The resulting interdependence structure is confusing and difficult to understand.
2. An object that references very many other objects and communicates directly with those objects makes it difficult to duplicate the object.


3. Want to customize a behavior that is distributed across multiple classes. * Do not want to generate too many subclasses.

Many other available links: http://blog.csdn.net/chenhuade85/article/details/8141831





The behavioral pattern of Java Classic 23 design patterns (II.)

Related Article

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.