The beauty of Java [from cainiao to master Evolution] Design Mode 4

Source: Internet
Author: User

If you have any questions during reading, please contact egg in time.
Email:
Xtfggef@gmail.comWeibo:Http://weibo.com/xtfggef
Reprint please explain the source: http://blog.csdn.net/zhangerqing

In fact, every design pattern is a very important idea and looks familiar. It is actually because we are involved in everything we learn, even though sometimes we don't know, in fact, it is embodied everywhere in the design of Java itself, such as AWT, JDBC, Collection class, Io pipeline or Web framework. The design mode is everywhere. Because we have limited space, it is difficult to explain every design pattern in detail, but I will do my best to clarify the meaning in the limited space and space, it makes everyone better understand. If this chapter is not surprising, it should be the last lecture of the design model. First, let's look at the figure starting with the previous article:

This chapter describes the third and fourth categories.

19. Memento)

The main purpose is to save a certain state of an object so that the object can be restored at an appropriate time. I personally think that the backup mode is more vivid. In general, assume that there is an original Class, A has various attributes. A can decide the attributes to be backed up. Memorandum Class B is used to store some internal states of A. Class C is used to store memos and can only be stored, cannot be modified. Make a picture to analyze:

The original class is the original class. It contains the attribute value to be saved and creates a memorandum class to save the value. The memento class is the memorandum class, and the storage class is the storage memorandum class. It is easy to understand this mode because it holds instances of the memento class. View the source code directly:

public class Original {private String value;public String getValue() {return value;}public void setValue(String value) {this.value = value;}public Original(String value) {this.value = value;}public Memento createMemento(){return new Memento(value);}public void restoreMemento(Memento memento){this.value = memento.getValue();}}
public class Memento {private String value;public Memento(String value) {this.value = value;}public String getValue() {return value;}public void setValue(String value) {this.value = value;}}
public class Storage {private Memento memento;public Storage(Memento memento) {this.memento = memento;}public Memento getMemento() {return memento;}public void setMemento(Memento memento) {this.memento = memento;}}

Test class:

Public class test {public static void main (string [] ARGs) {// create the original Class Original origi = new original ("egg "); // create a memorandum storage = new storage (origi. creatememento (); // modify the status of the original class system. out. println ("initialization status:" + origi. getvalue (); origi. setvalue ("niu"); system. out. println ("the modified status is:" + origi. getvalue (); // returns the original class status origi. restorememento (storage. getmemento (); system. out. println ("the restored status is:" + origi. getvalue ());}}

Output:

Initialization status: Egg
The modified status is Niu.
The restored status is egg.

Simple Description: when the original class is created, the value is initialized to egg. After modification, the value of the value is set to Niu, And the last and second rows are restored. The result is successfully restored. In fact, I think this mode is the most vivid.

20. State)

The core idea is: it is easy to understand when the object's status changes and its behavior changes at the same time! Take qq For example, there are several statuses, such as online, stealth, and busy. Each status corresponds to a different operation, and your friends can also see your status. Therefore, the status mode has two points: 1. You can change the status to obtain different behaviors. 2. Your friends can see your changes at the same time. Figure:

The state class is a state class, and the context class can be switched. Let's look at the Code:

Package COM. xtfggef. DP. state;/*** core class of the state class * 2012-12-1 * @ author erqing **/public class State {private string value; Public String getvalue () {return value ;} public void setvalue (string value) {This. value = value;} public void Method1 () {system. out. println ("execute the first opt! ");} Public void method2 () {system. Out. println (" execute the second opt! ");}}
Package COM. xtfggef. DP. state;/*** status mode switch class 2012-12-1 * @ author erqing **/public class context {private State state; public context (State state) {This. state = State;} public State getstate () {return state;} public void setstate (State state) {This. state = State;} public void method () {If (state. getvalue (). equals ("state1") {state. method1 ();} else if (state. getvalue (). equals ("state2") {state. method2 ();}}}

Test class:

Public class test {public static void main (string [] ARGs) {state = new state (); Context context = new context (State); // set the first state. setvalue ("state1"); context. method (); // sets the second State. setvalue ("state2"); context. method ();}}

Output:

Execute the first opt!
Execute the second opt!

According to this feature, the status mode is widely used in daily development. Especially when we are website users, we sometimes want to differentiate some of their functions based on certain attributes of objects, for example, simple permission control.
21. Visitor mode (visitor)

The visitor mode decouples the data structure and the operation acting on the structure, allowing the operation set to evolve relatively freely. The visitor mode is suitable for systems with relatively stable data structures and easy-to-change algorithms. The visitor mode makes it easy to increase algorithm operations. If the system data structure objects are easy to change and new data objects are often added, the visitor mode is not suitable. The advantage of the visitor mode is that it is easy to add operations, because adding operations means adding new visitors. The visitor mode aggregates relevant behaviors into a visitor object, and its changes do not affect the system data structure. The disadvantage is that it is very difficult to add new data structures. -- From encyclopedia

Simply put, the visitor mode is a way to separate the data structure and behavior of objects, this allows you to dynamically add new operations to a visitor without any other modifications. Simple relationship diagram:

Let's take a look at the original code: A visitor class that stores the objects to be accessed,

public interface Visitor {public void visit(Subject sub);}
public class MyVisitor implements Visitor {@Overridepublic void visit(Subject sub) {System.out.println("visit the subject:"+sub.getSubject());}}

The subject class, the accept method, accepts the object to be accessed, getsubject () gets the attribute to be accessed,

public interface Subject {public void accept(Visitor visitor);public String getSubject();}
public class MySubject implements Subject {@Overridepublic void accept(Visitor visitor) {visitor.visit(this);}@Overridepublic String getSubject() {return "love";}}

Test:

public class Test {public static void main(String[] args) {Visitor visitor = new MyVisitor();Subject sub = new MySubject();sub.accept(visitor);}}

Output: Visit the subject: Love

This mode applies to scenarios: if we want to add new features to an existing class, we have to consider a few things: 1. Will the new features have compatibility problems with existing features? 2. Will it be added later? 3. What if the class does not allow code modification? In the face of these problems, the best solution is to use the visitor mode. The visitor mode applies to systems with relatively stable data structures and decouples data structures and algorithms,
22. Mediator)

The intermediary mode is also used to reduce the coupling between classes, because if there is a dependency between classes, it is not conducive to function expansion and maintenance, because as long as you modify an object, other associated objects must be modified. If you use the intermediary mode, you only need to care about the relationship with the mediator class. The relationship and scheduling between the specific class classes can be handed over to the Mediator class. This is a bit like the role of the spring container. First look at the figure:

The user class has a unified interface. user1 and user2 are different objects and are associated with each other. If the intermediary mode is not used, the two must hold references to each other. In this way, the coupling between the two is very high, to decouple, the mediator class is introduced and a unified interface is provided. For its implementation class, mymediator holds instances of user1 and user2 to control user1 and user2. In this way, user1 and user2 are independent of each other. They only need to maintain a good relationship with mediator, and the rest are maintained by the mymediator class! Basic implementation:

public interface Mediator {public void createMediator();public void workAll();}
public class MyMediator implements Mediator {private User user1;private User user2;public User getUser1() {return user1;}public User getUser2() {return user2;}@Overridepublic void createMediator() {user1 = new User1(this);user2 = new User2(this);}@Overridepublic void workAll() {user1.work();user2.work();}}
public abstract class User {private Mediator mediator;public Mediator getMediator(){return mediator;}public User(Mediator mediator) {this.mediator = mediator;}public abstract void work();}
public class User1 extends User {public User1(Mediator mediator){super(mediator);}@Overridepublic void work() {System.out.println("user1 exe!");}}
public class User2 extends User {public User2(Mediator mediator){super(mediator);}@Overridepublic void work() {System.out.println("user2 exe!");}}

Test class:

public class Test {public static void main(String[] args) {Mediator mediator = new MyMediator();mediator.createMediator();mediator.workAll();}}

Output:

User1 EXE!
User2 EXE!
23. interpreter mode (Interpreter)
The interpreter mode is our last talk. It is generally used in the development of compilers in OOP development, so it has a narrow application scope.

The context class is a context class, and plus and minus are used for computing implementation. The Code is as follows:

public interface Expression {public int interpret(Context context);}
public class Plus implements Expression {@Overridepublic int interpret(Context context) {return context.getNum1()+context.getNum2();}}
public class Minus implements Expression {@Overridepublic int interpret(Context context) {return context.getNum1()-context.getNum2();}}
public class Context {private int num1;private int num2;public Context(int num1, int num2) {this.num1 = num1;this.num2 = num2;}public int getNum1() {return num1;}public void setNum1(int num1) {this.num1 = num1;}public int getNum2() {return num2;}public void setNum2(int num2) {this.num2 = num2;}}
Public class test {public static void main (string [] ARGs) {// calculate the value of 9 + 2-8 int result = new minus (). interpret (new context (New plus (). interpret (new context (9, 2), 8); system. out. println (result );}}

The correct result is output: 3.

Basically, the interpreter mode is used for various interpreters, such as regular expressions!

The design pattern is just like this. The overall feeling is a bit simple. Indeed, such a little space is not enough to fully elaborate on the entire 23 design patterns, here, readers can take it as a theoretical basis to learn. Through these four blog posts, I have a basic concept. Although I am a little simple, I can basically explain the problems and their characteristics, if you are interested, you can continue your research! At the same time, I will keep updating and try to make up for all the omissions and correction deficiencies. Readers are welcome to make suggestions in a timely manner. Let's study together! The Code involved in the project has been put into my resources: http://download.csdn.net/detail/zhangerqing/4835830 (because I don't like to get without work, so no points, only set 5, if someone really has no points and is in urgent need, contact me and I will send it to you ).

If you have any questions during reading, contact egg.

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

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.