⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 restrictedclass.java

📁 内存受限系统软件开发一书的代码。(虽不及Gang of Four的模式掷地有声
💻 JAVA
字号:
import  java.util.*;

class RestrictedClass 
{
    static final int maxNumberOfInstances = 5;
    static int numberOfInstances = 0;

    public RestrictedClass() {

        System.out.print("+");

        // even if we chuck a wobbly, the object still gets created. d'oh.
        // unless another constructor sequesters a reference away somewhere
        // widely considered as evil, you can never get a referece to the object
        // but it will still get finalised

        numberOfInstances++;

        if (numberOfInstances > maxNumberOfInstances) {
            System.gc();
        }
        if (numberOfInstances > maxNumberOfInstances) {
            throw new OutOfMemoryError("RestrictedClass can only have " + 
                                       maxNumberOfInstances + " instances");
        }
    }


    public void finalize() {
        --numberOfInstances;
        System.out.print("-");
        assert(numberOfInstances >= 0, "less than zero instances");
    }


    public static void main( String args[] )
    {

        test1();
        test2();

        System.out.println("done!");
    }

    public static void test1() {

        assert( numberOfInstances == 0 , "aint no instances" );

        Vector shovel = new Vector();
        int i = 0;
        try {
            
            for (; i < 10; i++) {
                System.out.print(".");
                shovel.addElement(new RestrictedClass());
            }

        } catch (OutOfMemoryError oom) {
            System.out.print("OOM!"); }

        assert ( shovel.size() == 5, "shovel.size() == " + shovel.size() + " != 5" );
    }

    public static void test2() {
        System.gc();
        assert( numberOfInstances == 0 , "aint no instances" + numberOfInstances );

        Vector shovel = new Vector();
        int i = 0;
        try {
            
            for (; i < 10; i++) {
                System.out.print("*");
                shovel.addElement(new RestrictedClass());
                new RestrictedClass();
                new RestrictedClass();
            }

        } catch (OutOfMemoryError oom) {
            System.out.print("OOM!"); }

        assert ( shovel.size() == 5, "shovel.size() == " + shovel.size() + " != 5" );
    }

    protected static void assert (boolean  assertion, String excuse) {
        if  (!assertion) { throw new RuntimeException(excuse);}
    }
};


⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -