Java classic 23 design patterns: behavioral patterns (1) and 23 Design Patterns

Source: Internet
Author: User

Java classic 23 design patterns: behavioral patterns (1) and 23 Design Patterns

There are 11 behavioral design patterns: Chain of Responsibility (responsible Chain mode), Command (Command mode), Interpreter (Interpreter mode), and Iterator (Iterator mode) mediator (intermediary mode), Memento (memorandum mode), Observer (Observer mode), State (State mode), Strategy (Policy mode), TemplateMethod (template method) and Visitor (Visitor mode). This article introduces the first two of these 11 behavior patterns.

I. Responsibility Chain Model

So that multiple objects have the opportunity to process the request, so as to avoid coupling between the request sender and the receiver. Connect these objects into a chain and pass the request according to the chain until an object processes it. Let's look at a simple example:

1. Handler defines an interface for processing requests. (Optional) Implement the successor chain.

Public interface RequestHandle {
Void handleRequest (Request request );
}

2. ConcreteHandler processes the requests it is responsible. Can access its successor. If the request can be processed, it will be processed; otherwise, the request will be forwarded to its successor.

Public class HRRequestHandle implements RequestHandle {


Public void handleRequest (Request request ){
If (request instanceof DimissionRequest ){
System. out. println ("to resign, personnel approval! ");
}
System. out. println ("request completed *");
}
}

The two types of ConcreteHandler can not only process the responsible request, but also forward the request to its successor.

Public class PMRequestHandle implements RequestHandle {Req * estHandle rh; public PMRequestHandle (RequestHandle * h) {this. rh = rh;} public void handle * equest (Request request) {if (request instanceof AddMoneyRequest) {System. out. println ("to raise the salary, approved by the Project Manager! *);} Else {rh. handleRequest (request) ;}} public class TLRequestHandle implements RequestHandle {RequestHandle rh; public TLRequestHandle (RequestHand * e rh) {this. rh = rh;} public void handleRequest (Request request) {if (request instanceof LeaveRe * uest) {System. ou *. println ("to ask for leave, approved by the project leader! ") ;}Else {rh. handleRequest (request );}}}

3. The Client submits a request to the ConcreteHandler object on the chain.

Public class Test {public static void main (String [] args) {RequestHa * dle hr = * ew HRRequ * stHandle (); requ * stHandle pm = new P * RequestHandle (hr); RequestHandle tl = new TLRequestHandle (pm); // The team leader processes the resignation Request request = new DimissionRequest () * tl. handleRequest (request); System. out. println ("============"); // team leader handles the salary increase request = new AddMoneyRequest (); tl. handleRequ * st (request); System. out. println ("========"); // The project manager handles the resignation Request requ * st = ne * Dimissio * Request (); pm. handleRequest (request );}}
Running result:

To resign, personnel approval!
Request completed
=========* ====
To raise the salary, the Project Manager approves it!
==========
To resign, personnel approval!
Request completed
After a brief analysis of the test code, the first three sentences new three different entities, RequestHandler, passed to him in pm tl their successors. The successor of pm is hr, and the successor of tl is pm. The successor is who can continue to process the request if you cannot process the current request. Then a new DimissionRequest request is sent to the tl for processing. Obviously, if the tl is not processed, the tl will let the pm process the request. Pm does not matter, let hr management. In the end, the handleMessage of hr processes the request. The following are similar.

This mode of responsibility chain is similar to the drum-and-teaser game. For details, see the link analysis.

Applicability:
1. There are multiple objects that can process a request, and the object that processes the request is automatically determined at the runtime.
2. You * submit a request to one of multiple objects without specifying the receiver explicitly.
3. The object set that can process a request should be dynamically specified.

Ii. Command mode

Encapsulate a request as an object so that you can parameterize the customer with different requests, queue requests or record request logs, and support unrecoverable operations.

1. Cycler
Know how to implement * operations related to executing a request. Any class can be used as a receiver.

Public class extends er {


Public void receive (){
System. out. println ("This is Receive class! ");
}
}

2. Command declares the interface for executing the operation.

Public abstract class command {

Protected extends er;

Public Command (extends er extends ER ){
This. Cycler = Cycler;
}

Public abstract void execute ();
}

3. ConcreteCommand binds a receiver object to an action. Call the corresponding operation of the receiver to Execute.

Public class CommandImpl extends Comman *{


Public CommandImpl (Receiv * r receiver ){
Super (Explorer );
}

Pu * lic void * xecute *){
Receiver. request ();
}
}

4. Invoker requires the command to execute the request.

Public class Invoker {


Private Command command;

Public void setCommand (Command command ){
This. command = command;
}

Public void execute (){
Command.exe cute ();
}
}

Test code:

Public class Test {


Public static void main (String [] args ){
Extends er rec = new extends Er ();
Command cmd = new CommandImpl (rec );
Invoker I = new Invoker ();
I. setCommand (cmd );
I .exe cute ();
}
}

Applicability
1. abstract the action to be executed to parameterize an object.
2. Specify, sort, and execute requests at different times.
3. cancelling is supported.
4. The log can be modified so that the * modifications can be redone when the system crashes.
5. construct a system using high-level operations built on primitive operations.

Command mode reference: http://www.cnblogs.com/devinzhang/archive/2012/01/06/2315235.html


Java 23 design modes

There are three types of design patterns: creation, structure, and behavior.
The creation types include:
I. Singleton, Singleton mode: ensure that a class has only one instance and provide a global access point to it.
2. Abstract Factory: provides an interface for creating a series of related or mutually dependent objects without specifying their specific classes.
3. Factory Method: Define an interface used to create objects, and let the subclass decide which class to instantiate. Factory Method delays the instantiation of a class to the subclass.
4. Builder: separates the construction of a complex object from its representation, so that different representations can be created during the same construction process.
5. Prototype: Use a Prototype instance to specify the type of the object to be created, and copy the Prototype to create a new object.
Behavior types:
6. Iterator: provides a method to access each element of an aggregate object sequentially without exposing the internal representation of the object.
7. Observer: Observer mode: defines one-to-many dependencies between objects. When the status of an object changes, all objects dependent on it will be automatically updated by notification.
8. Template Method: defines the skeleton of an algorithm in an operation, and delays some steps to the subclass, templateMethod allows the subclass to redefine a specific step without changing the structure of an algorithm.
9. Command: encapsulate a request as an object so that you can parameterize the customer with different requests, queue requests and record request logs, and supports unrecoverable operations.
10. State: allows an object to change its behavior when its internal State changes. The object seems to have changed its class.
11. Strategy: Define a series of algorithms, encapsulate them one by one, and enable them to replace each other. This mode allows algorithms to be independent of customers who use them.
12. China of Responsibility, Responsibility chain mode: Enables multiple objects to process requests to avoid coupling between the request sender and receiver.
13. Mediator: uses an intermediary object to encapsulate object interaction of some columns.
14. Visitor, Visitor mode: indicates an operation that acts on each element in an object structure. It allows you to define new operations that act on this element without changing the element classes.
15th, Interpreter, Interpreter mode: a language is defined to define a representation of its grammar and an Interpreter. This Interpreter uses this representation to explain sentences in the language.
16. Memento: capture the internal state of an object without interrupting the object, and save the state outside the object.
There are:
17. Composite: Composite combines objects into a tree structure to represent the relationship between parts of the whole. Composite makes the use of a single object and a Composite object consistent.
18. Facade, appearance mode: provides a consistent interface for a group of interfaces in the subsystem. fa? Ade provides a high-level interface, which makes the subsystem easier to use.
19. Proxy: provides a Proxy for other objects to control access to this object.
20. Adapter: the Adapter mode converts a class of interfaces into another interface that the customer wants. The Adapter mode makes those classes unable to work together due to interface incompatibility.
21. Decrator: the Decorator mode dynamically adds some additional responsibilities to an object. In terms of the added functions, the Decorator mode is more flexible than the subclass generation mode.
22. Bridge: link the abstract Part with its implementation... the remaining full text>

In Java, what are the 23 design patterns that must be understood?

1. Simple Factory Pattern)
2. Builder Pattern)
3. Strategy Mode
4. Factory Method Pattern)
5. Abstract Factory)
6. Command Pattern)
7. Template Method)
8. Single Pattern)
9. Prototype Pattern)

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.