Thinking In Patterns

来源:互联网 发布:applewatch怎么解锁mac 编辑:程序博客网 时间:2024/04/29 22:10

首先要用到静态类的概念:静态类是指在一个类的内部,又定义了一个静态的内部类。内部类是指只在该类中使用到内部类,static指的是随着类的加载就会被调用,而不是类对象的创建。点击打开链接  

       静态内部类的用法包括如下:

        (1) 使用静态内部类设置主程序入口

public class MainInStaticClass {    static class Main{        public static void main(String[] args){        new MainInStaticClass().print();    }     public void print(){        System.out.println("main in static inner class");    }}  public class TestMain {    public static void main(String[] args) {        new MainInStaticClass.Main.main();    }}

//: singleton:PoolManager.java package singleton; import java.util.*;  public class PoolManager { private static class PoolItem { boolean inUse = false; Object item; PoolItem(Object item) { this.item = item; } } private ArrayList items = new ArrayList(); public void add(Object item) { items.add(new PoolItem(item)); } static class EmptyPoolException extends Exception {} public Object get() throws EmptyPoolException { for(int i = 0; i < items.size(); i++) { PoolItem pitem = (PoolItem)items.get(i); if(pitem.inUse == false) { pitem.inUse = true; return pitem.item; } } // Fail early: throw new EmptyPoolException(); // return null; // Delayed failure } public void release(Object item) { for(int i = 0; i < items.size(); i++) { PoolItem pitem = (PoolItem)items.get(i); if(item == pitem.item){ pitem.inUse = false; return; } } throw new RuntimeException(item + " not found"); } } ///:~  //: singleton:ConnectionPoolDemo.java package singleton; import junit.framework.*;  interface Connection { Object get(); void set(Object x); }  class ConnectionImplementation implements Connection { public Object get() { return null; } public void set(Object s) {} }   class ConnectionPool { // A singleton private static PoolManager pool = new PoolManager(); public static void addConnections(int number) { for(int i = 0; i < number; i++) pool.add(new ConnectionImplementation()); } public static Connection getConnection() throws PoolManager.EmptyPoolException { return (Connection)pool.get(); } public static void releaseConnection(Connection c) { pool.release(c); } }  public class ConnectionPoolDemo extends TestCase {  static {   ConnectionPool.addConnections(5);  }  public void test() {   Connection c = null;   try {    c = ConnectionPool.getConnection();   } catch (PoolManager.EmptyPoolException e) {    throw new RuntimeException(e);   }   c.set(new Object());   c.get();   ConnectionPool.releaseConnection(c);  }  public void test2() {   Connection c = null;   try {    c = ConnectionPool.getConnection();   } catch (PoolManager.EmptyPoolException e) {    throw new RuntimeException(e);   }    c.set(new Object());    c.get();   ConnectionPool.releaseConnection(c);  }  public static void main(String args[]) {   junit.textui.TestRunner.run(ConnectionPoolDemo.class);  } } 



0 0