<rt id="bn8ez"></rt>
<label id="bn8ez"></label>

  • <span id="bn8ez"></span>

    <label id="bn8ez"><meter id="bn8ez"></meter></label>

    Scott@JAVA

    Java, 一杯濃濃的咖啡伴你到深夜

    《Effective Java》Chapter 2

    Chapter 2. Creating and Destroying Objects

    Item 1: Consider providing static factory methods instread of constructs
    eg. A static factory method from the class Boolean, which translates a boolean primitive value into a Booleam object reference:
    public static Boolean valueOf(boolean b) {
        
    return (b ? Boolean.TRUE : Boolean.FLASE);
    }
    Advantages:
    a) unlike constructors, they have names.
    b) unlike constructors, they are not required to create a new object each time they're invoked.
    c) unlike constructors, they can return an object of any subtype of their return type.
    (Atten plz: in JDK 5.0, there is Covariant Return Types)
    Disadvantages:
    a) classes without public or protected constructors cannot be subclassed.
    b) they are not readily distinguishable from other static methods.
       two names for static factory methods are becoming common:
          valueOf --- Return an instance that has, loosely speaking, the same value as its parameters.
          getInstance --- Return an instance that is described by its parameters but cannot be said to have the same value.

    Item 2: Enforce the singleton property with a private constructor
    One approach, the public static member is a final field:
    // Singleton with final field
    public class Elvis {
        
    public static final Elvis INSTANCE = new Elvis();
        
        
    private Elvis() {
            
        }

        
         
    // Remainder omitted
    }
    A second approach, a public static factory method is provided instead of the public static final field:
    // Singleton with static factory
    public class Elvis {
        
    private static final Elvis INSTANCE = new Elvis();
        
        
    private Elvis() {
            
        }

        
        
    public static Elvis getInstance() {
            
    return INSTANCE;
        }

        
         
    // Remainder omitted
    }

    Item 3: Enforce noninstantiability with a private constructor
    Attemping to enforce noninstantiablity by making a class abstract does not work.
    A class can be made noninstantiable by including a single explicit private constructor:
    // Noninstantiable utility class
    public class UtilityClass {
        
        
    // Suppress default constructor for noninstantiability
        private UtilityClass() {
            
    // This constructor will never be invoked
        }

        
         
    // Remainder omitted
    }

    Item 4: Avoid creating duplicate objects
    An object can always be reused if it is immutable.
    As an extreme example of what not to do: 
    String s = new String("silly"); // DON'T DO THIS!
    The improving version is simply the following: 
    String s = "No longer silly"
    You can often avoid creating duplicate objects by using static factory methods (Item 1) in preference to constructors on immutable classes that provide both.
    public class Person {
        
    private final Date birthDate;

        
    // Other fields omitted
        public Person(Date birthDate) {
            
    this.birthDate = birthDate;
        }


        
    // DON'T DO THIS!
        public boolean isBabyBoomer() {
            Calendar gmtCal 
    = Calendar.getInstance(TimeZone.getTimeZone("GMT"));
            gmtCal.set(
    1946, Calendar.JANUARY, 1000);
            Date boomStart 
    = gmtCal.getTime();
            gmtCal.set(
    1965, Calendar.JANUARY, 1000);
            Date boomEnd 
    = gmtCal.getTime();
            
    return birthDate.compareTo(boomStart) >= 0
                    
    && birthDate.compareTo(boomEnd) < 0;
        }

    }
    The isBabyBoomer method unnecessarily creates a new Calendar, TimeZone, and two Date instances each time it is invoked. The version that follows avoids this inefficiency with a static initializer:
    class Person {
        
    private final Date birthDate;

        
    public Person(Date birthDate) {
            
    this.birthDate = birthDate;
        }


        
    /**
         * The starting and ending dates of the baby boom.
         
    */

        
    private static final Date BOOM_START;

        
    private static final Date BOOM_END;
        
    static {
            Calendar gmtCal 
    = Calendar.getInstance(TimeZone.getTimeZone("GMT"));
            gmtCal.set(
    1946, Calendar.JANUARY, 1000);
            BOOM_START 
    = gmtCal.getTime();
            gmtCal.set(
    1965, Calendar.JANUARY, 1000);
            BOOM_END 
    = gmtCal.getTime();
        }


        
    public boolean isBabyBoomer() {
            
    return birthDate.compareTo(BOOM_START) >= 0
                    
    && birthDate.compareTo(BOOM_END) < 0;
        }

    }

    Item 5: Eliminate obsolete object reference
    // Can you spot the "memory leak"?
    public class Stack {
        
    private Object[] elements;

        
    private int size = 0;

        
    public Stack(int initialCapacity) {
            
    this.elements = new Object[initialCapacity];
        }


        
    public void push(Object e) {
            ensureCapacity();
            elements[size
    ++= e;
        }


        
    public Object pop() {
            
    if (size == 0)
                
    throw new EmptyStackException();
            
    return elements[--size];
        }


        
    /**
         * Ensure space for at least one more element, roughly doubling the capacity
         * each time the array needs to grow.
         
    */

        
    private void ensureCapacity() {
            
    if (elements.length == size) {
                Object[] oldElements 
    = elements;
                elements 
    = new Object[2 * elements.length + 1];
                System.arraycopy(oldElements, 
    0, elements, 0, size);
            }

        }

    }
    If a stack grows and then shrinks, the objects that were popped off the stack will not be garbage collected, even if the program using the stack has no more references to them. This is because the stack maintains obsolete references to these objects.
    public Object pop() {
        
    if (size==0)
            
    throw new EmptyStackException();
        Object result 
    = elements[--size];
        elements[size] 
    = null// Eliminate obsolete reference
        return result;
    }

    Item 6: Avoid finalizers
    Nothing time-critical should ever be done by a finalizer.
    You should never depend on a finalizer to update critical persistent state.
    Explicit termination methods are often used in combination with the try-finally construct to ensure prompt termination.
    Foo foo = new Foo();
    try {
        
    // Do what must be done with foo
        
    }
     finally {
        foo.terminate(); 
    // Explicit termination method
    }
    It is important to note that “finalizer chaining” is not performed automatically. If a class (other than Object) has a finalizer and a subclass overrides it, the subclass finalizer must invoke the superclass finalizer manually.
    // Manual finalizer chaining
    protected void finalize() throws Throwable {
        
    try {
            
    // Finalize subclass state
            
        }
     finally {
            
    super.finalize();
        }

    }
    Instead of putting the finalizer on the class requiring finalization, put the finalizer on an anonymous class (Item 18) whose sole purpose is to finalize its enclosing instance. A single instance of the anonymous class, called a finalizer guardian, is created for each instance of the enclosing class.
    // Finalizer Guardian idiom
    public class Foo {
        
    // Sole purpose of this object is to finalize outer Foo object
        private final Object finalizerGuardian = new Object() {
            
    protected void finalize() throws Throwable {
                
    // Finalize outer Foo object
                
            }

        }
    ;
         
    // Remainder omitted
    }

    posted on 2005-12-18 00:22 Scott@JAVA 閱讀(407) 評論(0)  編輯  收藏 所屬分類: Effective Java

    主站蜘蛛池模板: 日本视频一区在线观看免费| 中文字幕无线码中文字幕免费| 日本一卡精品视频免费| 亚洲日韩欧洲乱码AV夜夜摸| 一区二区在线免费视频| 亚洲日本中文字幕一区二区三区| 一级毛片高清免费播放| 亚洲毛片av日韩av无码| 香港特级三A毛片免费观看| 男人的天堂亚洲一区二区三区| 激情综合亚洲色婷婷五月| 无码人妻一区二区三区免费手机 | 亚洲一卡2卡4卡5卡6卡在线99 | 久久精品国产亚洲av四虎| 十八禁视频在线观看免费无码无遮挡骂过 | 免费国产va在线观看| 亚洲精品第一国产综合精品99| 一级中文字幕乱码免费| 奇米影视亚洲春色| 国产精品网站在线观看免费传媒| 亚洲av网址在线观看| 国产免费不卡视频| 亚洲七久久之综合七久久| 亚洲国产午夜福利在线播放 | 美女露隐私全部免费直播| 亚洲一级片免费看| 久久久久久久久久国产精品免费 | 亚洲精品无码永久在线观看你懂的| 日本中文字幕免费高清视频| 亚洲日韩中文字幕| 国产免费人成视频在线观看| 中文字幕不卡高清免费| 亚洲人成网站18禁止久久影院| 欧洲美熟女乱又伦免费视频| 一级毛片免费一级直接观看| 亚洲电影免费在线观看| 免费看a级黄色片| 男女一进一出抽搐免费视频| 亚洲成aⅴ人片在线观| 免费人成网站7777视频| 桃子视频在线观看高清免费视频|