Beginner's understanding of Java design pattern

The structural pattern of Java design pattern 1. Adapter mode Adapter mode of class 1.1 1.2 adapter mode for objects 1...
Adapter mode of class 1.1
1.2 adapter mode for objects
1.3 adapter mode of interface

The structural pattern of Java design pattern

1. Adapter mode

Convert the interface of one class into another interface that the customer wants, so that the classes that are incompatible with the original interface and cannot work together can work together.
The adapter pattern can be divided into class adapter pattern, object adapter pattern and interface adapter pattern.

Adapter mode of class 1.1

Transform the API of the adapted class into the API of the target class, create an adapted class, inherit the original class, and implement the new interface.

public interface Targetable { public void method1(); public void method2(); //New method added } public class Source { public void method1() { System.out.println("this is method1"); } } //Keep the original interface unchanged and use the adapter to generate a new interface public class Adapter extends Source implements Targetable { public void method2() { System.out.println("this is method2"); } }
public class Client { public static void main(String []args) { Targetable adapter =new Adapter(); adapter.method1(); adapter.method2(); } }

1.2 adapter mode for objects

The new interface is implemented by using delegation relation connection, and the original class is initialized. The method is directly called by the instance of the original class.

public interface Targetable { public void method1(); public void method2(); //New method } public class Source { public void method1() { System.out.println("this is method1"); } } public class Wrapper implements Targetable { private Source source; public Wrapper(Source source) { this.source = source; } public void method1() { source.method1(); } public void method2() { System.out.println("this is method2"); } }
public class Client { public static void main(String []args) { Targetable wrapper =new Wrapper(new Source()); wrapper.method1(); wrapper.method2(); } }

1.3 adapter mode of interface

We don't want the interface to implement all methods. We can create an abstract class Wrapper to implement all methods. When we write other classes, we can inherit the abstract classes.

public interface Targetable { public void method1(); public void method2(); } public class Wrapper implements Targetable { public void method1() {} public void method2() {} } public class Source extends Wrapper { public void method1() { System.out.println("this is method1"); } } public class Source1 extends Wrapper{ public void method2() { System.out.println("this is method2"); } }
public class Client { public static void main(String []args) { Source source =new Source(); source.method1(); source.method2(); Source1 source1 =new Source1(); source1.method1(); source1.method2(); } }
2. Decoration mode

Adding a new function to an object is equivalent to decorating a class to implement the original interface rewrite method, which needs to have the implementation of the original class.

public interface Sourceable { public void method(); } public class Source implements Sourceable { public void method() { System.out.println("this is method"); } } public class Decorator implements Sourceable { private Source source; public Decorator(Source source) { // TODO Auto-generated constructor stub super(); this.source = source; } @Override public void method() { // TODO Auto-generated method stub System.out.println("before"); source.method(); System.out.println("after"); } }
public class Client { public static void main(String []args) { Sourceable sourceable = new Decorator(new Source()); sourceable.method(); } }
3. Agent mode

Provides a proxy object for an object, and the proxy object controls the reference to the original object. Personal feeling is very similar to the decoration mode, but the agent mode may be more specific.

public interface Sourceable { public void method(); } public class Source implements Sourceable { public void method() { System.out.println("this is method"); } } public class Proxy implements Sourceable { private Source source; public Proxy(Source source) { this.source = source ; } public void method() { before(); source.method(); after(); } public void before() { System.out.println("one"); } public void after() { System.out.println("two"); } }
public class Client { public static void main(String []args) { Sourceable sourceable = new Proxy(new Source()); sourceable.method(); } }
4. Appearance mode

In order to solve the dependency between classes, just like spring, the relationship between classes is configured in the configuration file. The appearance pattern is to put their relationship in a class, reducing the coupling between classes.

public class CPU { public void startup() { System.out.println("CPU start-up"); } public void shutdown() { System.out.println("CPU close"); } } public class Memory { public void startup() { System.out.println("Memory start-up"); } public void shutdown() { System.out.println("Memory close"); } } public class Disk { public void startup() { System.out.println("Disk start-up"); } public void shutdown() { System.out.println("Disk close"); } } 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() { cpu.startup(); memory.startup(); disk.startup(); } public void shutdown() { disk.shutdown(); memory.shutdown(); cpu.shutdown(); } }
public class Client { public static void main(String []args) { Computer computer = new Computer(); computer.startup(); computer.shutdown(); } }
5. Bridge mode

The abstraction and realization are decoupled so that they can change independently. Similar to jdbc bridge drivermanager.

public interface Sourceable { public void method(); } public class Source implements Sourceable { public void method() { System.out.println("this is source"); } } public class Source1 implements Sourceable{ public void method() { System.out.println("this is source1"); } } public abstract class Bridge { private Sourceable sourceable; public Sourceable getSourceable() { return sourceable; } public void setSourceable(Sourceable sourceable) { this.sourceable = sourceable; } public void method() { sourceable.method(); } } public class MyBridge extends Bridge { public void method() { getSourceable().method(); } }
public class Client { public static void main(String []args) { Bridge bridge = new MyBridge(); Sourceable sourceable1 = new Source(); bridge.setSourceable(sourceable1); bridge.method(); Sourceable sourceable2 =new Source1(); bridge.setSourceable(sourceable2); bridge.method(); } }
6. Combination mode

Combine objects into a tree structure to represent the 'part whole' hierarchy.

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; } public void add(TreeNode node) { children.add(node); } public void remove(TreeNode node) { children.remove(node); } public Enumeration<TreeNode> getChildren(){ return children.elements(); } }
public class Client { public static void main(String []args) { TreeNode nodeA = new TreeNode("A"); TreeNode nodeB = new TreeNode("B"); TreeNode nodeC = new TreeNode("C"); nodeB.add(nodeC); nodeA.add(nodeB); } }
7. Enjoy yuan mode

This mode can realize object sharing, that is, shared pool. When there are many objects in the system, it can reduce the memory overhead, which is usually used together with the factory mode.

//Create jdbc connection pool public class ConnectionPool { private Vector<Connection> pool; private String url = "jdbc:mysql://localhost:3306/bs"; 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; public 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) { // TODO: handle exception e.printStackTrace(); }catch (SQLException e) { // TODO: handle exception e.printStackTrace(); } } } public synchronized void release() { pool.add(conn); } public synchronized Connection getConnection() { if(pool.size()>0) { Connection conn = pool.get(0); pool.remove(conn); return conn; }else return null; } }
//Compare connection pool with normal connection mode (100 times) public class Client { public static void main(String []args) { try { /*Time to create 100 connections using connection pool*/ ConnectionPool connPool= new ConnectionPool(); // SQL test statement String sql = "Select * from search"; // Set the start time of program operation long start = System.currentTimeMillis(); // Loop test 100 database connections for (int i = 0; i < 100; i++) { Connection conn = connPool.getConnection(); // Get an available connection from the connection Library Statement stmt = conn.createStatement(); ResultSet rs = stmt.executeQuery(sql); while (rs.next()) { String name = rs.getString("title"); System.out.println("title"+name); // System.out.println("query result" + name); } rs.close(); stmt.close(); connPool.release();// Release connection to connection pool after connection is used } System.out.println("Time spent using connection pool after 100 circular calls:"+ (System.currentTimeMillis() - start) + "ms"); // Set the start time of program operation start = System.currentTimeMillis(); /*Time to create 100 connections without using connection pool*/ // Import driver Class.forName("com.mysql.jdbc.Driver"); for (int i = 0; i < 100; i++) { // Create connection Connection conn = DriverManager.getConnection( "jdbc:mysql://localhost:3306/bs", "root", "root"); Statement stmt = conn.createStatement(); ResultSet rs = stmt.executeQuery(sql); while (rs.next()) { } rs.close(); stmt.close(); conn.close();// Close connection } System.out.println("Time spent without connection pool after 100 circular calls:" + (System.currentTimeMillis() - start) + "ms"); } catch (SQLException e) { e.printStackTrace(); } catch (ClassNotFoundException e) { e.printStackTrace(); } } }

4 June 2020, 08:41 | Views: 9115

Add new comment

For adding a comment, please log in
or create account

0 comments