- 论坛徽章:
- 0
|
什么时候用内嵌类?
呵呵,我也不是太明白,大概就是 text cursor 只知道某个特定的 text component
所以可以作为 text component 的 inner class
举个例子:
比如:我写了一个 ConnectionPool 类来处理和数据库的连接
我想每秒钟检查一下 ConnectionPool 中的 connection 是否 idle,
如果 idle ,就把它回收到 connectionPool 里
做这个工作的类叫做 ConnectionReaper,是一个线程
每秒运行一次,调用 ConnecitonPool 的 reapConnection() 方法
他只需知道 ConnectionPool ,其他都不需要知道
所以可以把 ConnectionReaper 作为 ConnectionPool 的一个 inner class
- public class ConnectionPool{
- // the connection array
- Connection[] connections;
- public ConnectionPool(){
- // init the connections
- }
- public Connection getConnection(){
- // return an idle connection
- }
- public void reapConnection(){
- // check each connection, if idle, return this connection to pool
- }
- class ConnectionReaper extends Thread{
- ConnectionPool pool;
- public ConnectionReaper(ConnectionPool pool){
- this.pool = pool;
- start();
- }
- public void run(){
- while(true){
- sleep(1000);
- pool.reapConnection();
- }
- }
- }
- }
复制代码 |
|