Skip to content

Latest commit

 

History

History
407 lines (325 loc) · 10 KB

裝飾者模式.md

File metadata and controls

407 lines (325 loc) · 10 KB

裝飾者模式

對象增強的手段

  • 繼承
    • 被增強的對象是固定的
    • 增強的內容是固定的
  • 裝飾者模式
    • 被增強的對象是可以切換的
    • 增強的內容是固定的
  • 動態代理
    • 被增強的對象可以切換: Service
    • 增強的內容也可以切換: 事務處理

繼承

缺點:

  1. 增強的內容是死的
  2. 被增強的對象是死的
class 咖啡類()
class 有糖咖啡 extends 咖啡類 {}
class 加奶咖啡 extends 咖啡類 {}
class 加鹽咖啡 extends 咖啡類 {}
class 加辣咖啡 extends 咖啡類 {}
class 加糖加奶 extends 加奶 {}

裝飾者模式

  1. 增強的內容是不能修改的
  2. 被增強的對象可以是任意的
class 咖啡類()
class 有糖咖啡 extends 咖啡類 {}
class 加奶咖啡 extends 咖啡類 {}
class 加鹽咖啡 extends 咖啡類 {}

咖啡 a = new 加糖();
咖啡 b = new 加鹽(a); //對 a 進行裝飾,就是給 a 加鹽
咖啡 c = new 加奶(b);
  • Java API: IO 流

    • 字節: InputStream, OutputStream
    • 字符: Reader, Writer
  • InputStream: FileInputStream: 節點流,就是和一個資源綁定再一起的(文件)。 BufferedInputStream: 他是裝飾流。創建時一定要給一個底層對象,不管給的是什麼流,都會給他添加緩衝區。

    FileInputStream in = new FileInputStrea("c:/1.jpg");
    BufferedInputStream b = new BufferedInputStrea(in);
    ObjectInputStream o = new ObjectInputStream(b);
    
  • 裝飾: 不知道被增強對象的具體類型時,可以使用。 是你還有你,一切拜託你

class MyConnection implements Connection { //是你
    //還有你
    private Connection con; //底層對象,被增強對象
    
    public MyConnection(Connection con) { //通過構造器傳遞底層對象
        this.con = con;
    }
    
    //一切拜託你
    public Statement createStatement() {
        return con.createStatement();
    }
    
    //增強點
    public void close() {
        把當前連接還給池
    }
}

Example

//ConnectionWrapper.java
import java.sql.Array;
import java.sql.Blob;
import java.sql.CallableStatement;
import java.sql.Clob;
import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.NClob;
import java.sql.PreparedStatement;
import java.sql.SQLClientInfoException;
import java.sql.SQLException;
import java.sql.SQLWarning;
import java.sql.SQLXML;
import java.sql.Savepoint;
import java.sql.Statement;
import java.sql.Struct;
import java.util.Map;
import java.util.Properties;
import java.util.concurrent.Executor;


public class ConnectionWrapper implements Connection {
	protected Connection con;
	
	public ConnectionWrapper(Connection con) {
		this.con = con;
	}
	
	public void close() throws SQLException {
		con.close();
	}
	
	public <T> T unwrap(Class<T> iface) throws SQLException {
		return con.unwrap(iface);
	}

	public boolean isWrapperFor(Class<?> iface) throws SQLException {
		return con.isWrapperFor(iface);
	}

	public Statement createStatement() throws SQLException {
		return con.createStatement();
	}

	public PreparedStatement prepareStatement(String sql) throws SQLException {
		return con.prepareStatement(sql);
	}

	public CallableStatement prepareCall(String sql) throws SQLException {
		return con.prepareCall(sql);
	}

	public String nativeSQL(String sql) throws SQLException {
		return con.nativeSQL(sql);
	}

	public void setAutoCommit(boolean autoCommit) throws SQLException {
		con.setAutoCommit(autoCommit);
	}

	public boolean getAutoCommit() throws SQLException {
		return con.getAutoCommit();
	}

	public void commit() throws SQLException {
		con.commit();
	}

	public void rollback() throws SQLException {
		con.rollback();
	}

	public boolean isClosed() throws SQLException {
		return con.isClosed();
	}

	public DatabaseMetaData getMetaData() throws SQLException {
		return con.getMetaData();
	}

	public void setReadOnly(boolean readOnly) throws SQLException {
		con.setReadOnly(readOnly);
	}

	public boolean isReadOnly() throws SQLException {
		return con.isReadOnly();
	}

	public void setCatalog(String catalog) throws SQLException {
		con.setCatalog(catalog);
	}

	public String getCatalog() throws SQLException {
		return con.getCatalog();
	}

	public void setTransactionIsolation(int level) throws SQLException {
		con.setTransactionIsolation(level);
	}

	public int getTransactionIsolation() throws SQLException {
		return con.getTransactionIsolation();
	}

	public SQLWarning getWarnings() throws SQLException {
		return con.getWarnings();
	}

	public void clearWarnings() throws SQLException {
		con.clearWarnings();
	}

	public Statement createStatement(int resultSetType, int resultSetConcurrency)
			throws SQLException {
		return con.createStatement();
	}

	public PreparedStatement prepareStatement(String sql, int resultSetType,
			int resultSetConcurrency) throws SQLException {
		return con.prepareStatement(sql);
	}

	public CallableStatement prepareCall(String sql, int resultSetType,
			int resultSetConcurrency) throws SQLException {
		return con.prepareCall(sql);
	}

	public Map<String, Class<?>> getTypeMap() throws SQLException {
		return con.getTypeMap();
	}

	public void setTypeMap(Map<String, Class<?>> map) throws SQLException {
		con.setTypeMap(map);
	}

	public void setHoldability(int holdability) throws SQLException {
		con.setHoldability(holdability);
	}

	public int getHoldability() throws SQLException {
		return con.getHoldability();
	}

	public Savepoint setSavepoint() throws SQLException {
		return con.setSavepoint();
	}

	public Savepoint setSavepoint(String name) throws SQLException {
		return con.setSavepoint(name);
	}

	public void rollback(Savepoint savepoint) throws SQLException {
		con.rollback(savepoint);
	}

	public void releaseSavepoint(Savepoint savepoint) throws SQLException {
		con.releaseSavepoint(savepoint);
	}

	public Statement createStatement(int resultSetType,
			int resultSetConcurrency, int resultSetHoldability)
			throws SQLException {
		return con.createStatement(resultSetType, resultSetConcurrency, resultSetHoldability);
	}

	public PreparedStatement prepareStatement(String sql, int resultSetType,
			int resultSetConcurrency, int resultSetHoldability)
			throws SQLException {
		return con.prepareStatement(sql, resultSetType, resultSetConcurrency, resultSetHoldability);
	}

	public CallableStatement prepareCall(String sql, int resultSetType,
			int resultSetConcurrency, int resultSetHoldability)
			throws SQLException {
		return con.prepareCall(sql);
	}

	public PreparedStatement prepareStatement(String sql, int autoGeneratedKeys)
			throws SQLException {
		return con.prepareStatement(sql, autoGeneratedKeys);
	}

	public PreparedStatement prepareStatement(String sql, int[] columnIndexes)
			throws SQLException {
		return con.prepareStatement(sql, columnIndexes);
	}

	public PreparedStatement prepareStatement(String sql, String[] columnNames)
			throws SQLException {
		return con.prepareStatement(sql, columnNames);
	}

	public Clob createClob() throws SQLException {
		return con.createClob();
	}

	public Blob createBlob() throws SQLException {
		return con.createBlob();
	}

	public NClob createNClob() throws SQLException {
		return con.createNClob();
	}

	public SQLXML createSQLXML() throws SQLException {
		return con.createSQLXML();
	}

	public boolean isValid(int timeout) throws SQLException {
		return con.isValid(timeout);
	}

	public void setClientInfo(String name, String value)
			throws SQLClientInfoException {
		con.setClientInfo(name, value);
	}

	public void setClientInfo(Properties properties)
			throws SQLClientInfoException {
		con.setClientInfo(properties);
	}

	public String getClientInfo(String name) throws SQLException {
		return con.getClientInfo(name);
	}

	public Properties getClientInfo() throws SQLException {
		return con.getClientInfo();
	}

	public Array createArrayOf(String typeName, Object[] elements)
			throws SQLException {
		return con.createArrayOf(typeName, elements);
	}

	public Struct createStruct(String typeName, Object[] attributes)
			throws SQLException {
		return con.createStruct(typeName, attributes);
	}

	public void setSchema(String schema) throws SQLException {
		con.setSchema(schema);
	}

	public String getSchema() throws SQLException {
		return con.getSchema();
	}

	public void abort(Executor executor) throws SQLException {
		con.abort(executor);
	}

	public void setNetworkTimeout(Executor executor, int milliseconds)
			throws SQLException {
		con.setNetworkTimeout(executor, milliseconds);
	}

	public int getNetworkTimeout() throws SQLException {
		return con.getNetworkTimeout();
	}
}

//MyConnection.java
import java.sql.Connection;
import java.sql.SQLException;

public class MyConnection extends ConnectionWrapper {
	public MyConnection(Connection con) {
		super(con);
	}
	
	public void close() throws SQLException {
		System.out.println("HaHa");
		super.close();
	}
}

//Demo7.java
import java.sql.Connection;
import java.sql.SQLException;

import org.apache.commons.dbcp.BasicDataSource;
import org.junit.Test;

/**
 * dbcp 連接池
 * @author jack870131
 *
 */
public class Demo7 {
	@Test
	public void fun1() throws SQLException {
		/*
		 * 1. 創建連接對象
		 * 2. 配置四大參數
		 * 3. 配置池參數
		 * 4. 得到連接對象
		 */
		//四大參數
		BasicDataSource dataSource = new BasicDataSource();
		dataSource.setDriverClassName("com.mysql.jdbc.Driver");
		dataSource.setUrl("jdbc:mysql://localhost:3306/mysql");
		dataSource.setUsername("root");
		dataSource.setPassword("tyler0131");
		
		//池參數
		dataSource.setMaxActive(20);
		dataSource.setMinIdle(3);
		dataSource.setMaxWait(1000);
		
		//得到連接對象
		Connection con = dataSource.getConnection();
		Connection con1 = new MyConnection(con);
		System.out.println(con1.getClass().getName());
		
		/**
		 * 連接池內部使用了四大參數創建了連接對象,即 mysql 驅動提供的 Connection
		 * 連接池使用 mysql 的連接對象進行了裝飾,只對 close() 方法進行了增強
		 * 裝飾之後的 Connection 的 close() 方法,用來把當前連接歸還給池
		 */
		con1.close(); //把連接歸還給池
	}
}