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

Source: Internet
Author: User

If you have any questions during reading, please contact egg in time.

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

If there is reprint, please explain the source: http://blog.csdn.net/zhangerqing

Next we will discuss the design patterns. In the previous article, I have finished five creation patterns. At the beginning of this chapter, I will talk about seven structural patterns: adapter mode, decoration mode, proxy mode, appearance mode, bridging mode, combination mode, and shared element mode. The object's adapter mode is the origin of various modes. Let's look at the figure below:

6. Adapter Mode)

The adapter mode converts an interface of a class to another interface that the client expects. The purpose is to eliminate the compatibility issues of the class caused by interface mismatch. There are three main types: Class adapter mode, Object Adapter mode, and interface adapter mode. First, let's take a lookClass adapter ModeFirst look at the class diagram:

The core idea is: there is a source class with a method to be adapted, targetable for the target interface, and the source function is extended to targetable through the adapter class, to see the code:

public class Source {public void method1() {System.out.println("this is original method!");}}
Public interface targetable {/* is the same as the method in the original class */Public void Method1 ();/* method of the new class */Public void method2 ();}
public class Adapter extends Source implements Targetable {@Overridepublic void method2() {System.out.println("this is the targetable method!");}}

The adapter class inherits the source class and implements the targetable interface. The following is a test class:

public class AdapterTest {public static void main(String[] args) {Targetable target = new Adapter();target.method1();target.method2();}}

Output:

This is original method!
This is the targetable method!

In this way, the implementation class of the targetable interface has the function of the source class.

Object Adapter Mode

The basic idea is the same as the adapter mode of the class. It only modifies the adapter class. Instead of inheriting the source class, this time it holds an instance of the source class to solve the compatibility problem. Figure:

 

You only need to modify the source code of the adapter class:

public class Wrapper implements Targetable {private Source source;public Wrapper(Source source){super();this.source = source;}@Overridepublic void method2() {System.out.println("this is the targetable method!");}@Overridepublic void method1() {source.method1();}}

Test class:

public class AdapterTest {public static void main(String[] args) {Source source = new Source();Targetable target = new Wrapper(source);target.method1();target.method2();}}

The output is the same as the first one, but the adaptation method is different.

The third adapter mode isInterface adapter ModeThe interface adapter is like this: Sometimes an interface we write has multiple abstract methods. When we write the implementation class of this interface, we must implement all the methods of this interface, this is obviously a waste of time, because not all methods are needed, and sometimes only some are needed. To solve this problem, we introduce the interface adapter mode, with the help of an abstract class, this abstract class implements this interface and implements all the methods. Instead of dealing with the original interface, we only get in touch with this abstract class, so we write a class, inherit this abstract class and rewrite the method we need. Take a look at the class diagram:

This is easy to understand. In actual development, we often encounter many methods defined in this interface, so that sometimes we don't need them all in some implementation classes. Check the Code:

public interface Sourceable {public void method1();public void method2();}

Abstract class wrapper2:

public abstract class Wrapper2 implements Sourceable{public void method1(){}public void method2(){}}
public class SourceSub1 extends Wrapper2 {public void method1(){System.out.println("the sourceable interface's first Sub1!");}}
public class SourceSub2 extends Wrapper2 {public void method2(){System.out.println("the sourceable interface's second Sub2!");}}
public class WrapperTest {public static void main(String[] args) {Sourceable source1 = new SourceSub1();Sourceable source2 = new SourceSub2();source1.method1();source1.method2();source2.method1();source2.method2();}}

Test output:

The sourceable interface's first sub1!
The sourceable interface's second sub2!

Our results have been achieved!

To sum up the application scenarios of the three adapter modes:

Class adapter mode: When you wantA ClassConvert to meetAnother new interfaceYou can use the class adapter mode to create a new class, inherit the original class, and implement a new interface.

Object Adapter mode: When you want to convert an object to an object that meets another new interface, you can create a Wrapper class and hold an instance of the original class. In the Wrapper class method, call the method of the instance.

Interface adapter mode: if you do not want to implement all the methods in an interface, you can create an abstract class wrapper to implement all the methods. When writing other classes, inherit the abstract class.

7. decorator)

As the name suggests, the decoration mode adds some new functions to an object and is dynamic. It requires that the decoration object and the decorated object implement the same interface. The decoration object holds the instance of the decorated object, the diagram is as follows:

The source class is a decoration class, And the decorator class is a decoration class. You can dynamically add some functions to the source class. The Code is as follows:

public interface Sourceable {public void method();}
public class Source implements Sourceable {@Overridepublic void method() {System.out.println("the original method!");}}
public class Decorator implements Sourceable {private Sourceable source;public Decorator(Sourceable source){super();this.source = source;}@Overridepublic void method() {System.out.println("before decorator!");source.method();System.out.println("after decorator!");}}

Test class:

public class DecoratorTest {public static void main(String[] args) {Sourceable source = new Source();Sourceable obj = new Decorator(source);obj.method();}}

Output:

Before decorator!
The original method!
After decorator!

Decorator mode application scenarios:

1. You need to extend the functions of a class.

2. dynamically Add a function for an object and undo it dynamically. (Inheritance cannot do this. The inherited functions are static and cannot be added or deleted dynamically .)

Disadvantage: too many similar objects are generated, so it is not easy to troubleshoot!

8. Proxy)

In fact, the name of each mode indicates the role of this mode. The proxy mode is to add one more proxy class to perform some operations for the original object. For example, we go back to the intermediary when renting a house. Why? Because you do not have comprehensive information about the houses in the region, I hope you can find someone you are more familiar with to help you. This is what proxy means here. If we go to court sometimes, we need to ask a lawyer. Because he has expertise in law, he can operate for us and express his thoughts. Let's take a look at the relationship diagram:

As described above, the proxy mode is easy to understand. Let's look at the Code:

public interface Sourceable {public void method();}
public class Source implements Sourceable {@Overridepublic void method() {System.out.println("the original method!");}}
public class Proxy implements Sourceable {private Source source;public Proxy(){super();this.source = new Source();}@Overridepublic void method() {before();source.method();atfer();}private void atfer() {System.out.println("after proxy!");}private void before() {System.out.println("before proxy!");}}

Test class:

public class ProxyTest {public static void main(String[] args) {Sourceable source = new Proxy();source.method();}}

Output:

Before proxy!
The original method!
After proxy!

Application scenarios of proxy mode:

If the existing method needs to be improved when used, there are two methods:

1. modify the original method to adapt. This violates the principle of "opening to extensions and disabling modifications.

2. A proxy class is used to call the original method and control the results. This method is the proxy mode.

With the proxy mode, you can clearly divide functions and facilitate later maintenance!

9. Facade)

The appearance mode is used to solve the dependency between the class and the class house. Like spring, you can configure the relationship between the class and the class to the configuration file, the appearance mode places their relationships in a facade class, reducing the coupling between classes. This mode does not involve interfaces, take a look at the class diagram below: (we take the Startup Process of a computer as an example)

Let's first look at the implementation class:

public class CPU {public void startup(){System.out.println("cpu startup!");}public void shutdown(){System.out.println("cpu shutdown!");}}
public class Memory {public void startup(){System.out.println("memory startup!");}public void shutdown(){System.out.println("memory shutdown!");}}
public class Disk {public void startup(){System.out.println("disk startup!");}public void shutdown(){System.out.println("disk shutdown!");}}
public class Computer {private CPU cpu;private Memory memory;private Disk disk;public Computer(){cpu = new CPU();memory = new Memory();disk = new Disk();}public void startup(){System.out.println("start the computer!");cpu.startup();memory.startup();disk.startup();System.out.println("start computer finished!");}public void shutdown(){System.out.println("begin to close the computer!");cpu.shutdown();memory.shutdown();disk.shutdown();System.out.println("computer closed!");}}

The user class is as follows:

public class User {public static void main(String[] args) {Computer computer = new Computer();computer.startup();computer.shutdown();}}

Output:

Start the computer!
CPU startup!
Memory startup!
Disk startup!
Start computer finished!
Begin to close the computer!
CPU shutdown!
Memory shutdown!
Disk shutdown!
Computer Closed!

If we do not have a computer class, the CPU, memory, and disk will hold instances for each other to create a relationship. This will cause serious dependencies and change a class, other classes may be modified. This is not what we want to see. With the computer class, the relationship between them is placed in the computer class, which plays a decoupling role, this is the appearance mode!

10. Bridge)

The Bridge Mode separates things from their specific implementations so that they can change independently. The purpose of bridging is:Decouples abstraction and implementation so that the two can change independently.Like our commonly used JDBC bridge drivermanager, when JDBC connects to a database, it switches between different databases, basically without having to move too much code or even no need to do anything, the reason is that JDBC provides a unified interface, and each database provides its own implementation. You can use a program called a database driver to bridge the interface. Let's look at the relationship diagram:

Implementation Code:

First define the interface:

public interface Sourceable {public void method();}

Define two implementation classes respectively:

public class SourceSub1 implements Sourceable {@Overridepublic void method() {System.out.println("this is the first sub!");}}
public class SourceSub2 implements Sourceable {@Overridepublic void method() {System.out.println("this is the second sub!");}}

Define a bridge and hold an instance of sourceable:

public abstract class Bridge {private Sourceable source;public void method(){source.method();}public Sourceable getSource() {return source;}public void setSource(Sourceable source) {this.source = source;}}
public class MyBridge extends Bridge {public void method(){getSource().method();}}

Test class:

Public class bridgetest {public static void main (string [] ARGs) {bridge = new mybridge ();/* call the first object */sourceable source1 = new sourcesub1 (); bridge. setsource (source1); bridge. method ();/* call the second object */sourceable source2 = new sourcesub2 (); bridge. setsource (source2); bridge. method ();}}

Output:

This is the first sub!
This is the second sub!

In this way, we call the bridge class to call the sourcesub1 and sourcesub2 implementation classes of the interface sourceable. Next, I will draw a picture, and you will understand it, because this figure is the principle of our JDBC connection, with the foundation of database learning.

11. Composite)

The combination mode is sometimes calledPart-wholeThis mode is more convenient for handling issues similar to tree structures. Let's look at the relationship diagram:

Let's look at the Code:

Public class treenode {private string name; private treenode parent; private vector <treenode> Children = new vector <treenode> (); Public treenode (string name) {This. name = Name;} Public String getname () {return name;} public void setname (string name) {This. name = Name;} public treenode getparent () {return parent;} public void setparent (treenode parent) {This. parent = parent;} // Add the child node public void add (treenode node) {children. add (node);} // Delete the child node public void remove (treenode node) {children. remove (node);} // get the child node public enumeration <treenode> getchildren () {return children. elements ();}}
public class Tree {TreeNode root = null;public Tree(String name) {root = new TreeNode(name);}public static void main(String[] args) {Tree tree = new Tree("A");TreeNode nodeB = new TreeNode("B");TreeNode nodeC = new TreeNode("C");nodeB.add(nodeC);tree.root.add(nodeB);System.out.println("build the tree finished!");}}

Use Cases: Multiple objects are combined for operations. They are often used to represent tree structures, such as binary trees and numbers.

12. flyweight)

The primary purpose of the metadata mode is to share objects, that is, the shared pool. When there are many objects in the system, the memory overhead can be reduced, which is usually used together with the factory mode.

Flyweightfactory is responsible for creating and managing the metadata. When a client requests, the factory needs to check whether there are qualified objects in the current Object pool. If yes, an existing object is returned. If no, creates a new object, and flyweight is a superclass. When talking about the shared pool, we can easily think of the JDBC connection pool in Java. Considering the characteristics of each connection, we can easily sum up the following objects suitable for sharing, they have some common attributes. For database connection pools, URL, driverclassname, username, password, and dbname attributes are the same for each connection, therefore, it is suitable to use the metadata mode for processing. To create a factory class, use the aforementioned similar attributes as internal data, and use the others as external data. When the method is called, it is passed as a parameter, this saves space and reduces the number of instances.

Let's look at an example:

Check the database connection pool code:

Public class connectionpool {private vector <connection> pool;/* Public attribute */private string url = "JDBC: mysql: // localhost: 3306/test "; private string username = "root"; private string Password = "root"; private string driverclassname = "com. mySQL. JDBC. driver "; private int poolsize = 100; Private Static connectionpool instance = NULL; connection conn = NULL;/* constructor for initialization */private connectionpool () {pool = new vector <connection> (poolsize); For (INT I = 0; I <poolsize; I ++) {try {class. forname (driverclassname); Conn = drivermanager. getconnection (URL, username, password); pool. add (conn);} catch (classnotfoundexception e) {e. printstacktrace ();} catch (sqlexception e) {e. printstacktrace () ;}}/ * returned connection pool */Public synchronized void release () {pool. add (conn);}/* returns a database connection in the connection pool */Public synchronized connection getconnection () {If (pool. size ()> 0) {connection conn = pool. get (0); pool. remove (conn); Return conn;} else {return NULL ;}}}

Through the management of the connection pool, the database connection is shared, and you do not need to re-create the connection every time. This saves the database re-creation overhead and improves the system performance! This chapter describes seven structural models. Due to space issues, we will take another chapter on the remaining 11 behavioral models. Please stay tuned!

If you have any questions, contact egg:

Email: 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.