Date d = Date.from(instant);
Set<Rank> faceCards = EnumSet.of(JACK, QUEEN, KING);
BigInteger prime = BigInteger.valueOf(Integer.MAX_VALUE);
StackWalker luke = StackWalker.getInstance(options);
Object newArray = Array.newInstance(classObject, arrayLen);
FileStore fs = Files.getFileStore(path);
BufferedReader br = Files.newBufferedReader(path);
List<Complaint> litany = Collections.list(legacyLitany);
public class NutritionFacts { private final int servingSize; // (mL) required private final int servings; // (per container) required private final int calories; // (per serving) optional private final int fat; // (g/serving) optional private final int sodium; // (mg/serving) optional private final int carbohydrate; // (g/serving) optional public NutritionFacts(int servingSize, int servings) { this(servingSize, servings, 0); } public NutritionFacts(int servingSize, int servings, int calories) { this(servingSize, servings, calories, 0); } public NutritionFacts(int servingSize, int servings, int calories, int fat) { this(servingSize, servings, calories, fat, 0); } public NutritionFacts(int servingSize, int servings, int calories, int fat, int sodium) { this(servingSize, servings, calories, fat, sodium, 0); } public NutritionFacts(int servingSize, int servings, int calories, int fat, int sodium, int carbohydrate) { this.servingSize = servingSize; this.servings = servings; this.calories = calories this.fat = fat this.sodium = sodium this.carbohydrate = carbohydrate; } }
public class NutritionFacts { private int servingSize = -1; // Required; no default value private int servings = -1; // Required; no default value private int calories = 0; private int fat = 0; private int sodium = 0; private int carbohydrate = 0; public NutritionFacts() {} // Setters public void setServingSize(int val) { servingSize = val; } public void setServings(int val) { servings = val; } public void setCalories(int val) { calories = val; } public void setFat(int val) { fat = val; } public void setSodium(int val) { sodium = val; } public void setCarbohydrate(int val) { carbohydrate = val; } }
缺點:html
構造過程被分到了多個調用中,一個JavaBean在其構造過程當中可能處於不一致的狀態。java
類沒法僅僅經過檢查構造器參數的有效性來保證一致性。數據庫
// Builder Pattern public class NutritionFacts { private final int servingSize; private final int servings; private final int calories; private final int fat; private final int sodium; private final int carbohydrate; public static class Builder { // Required parameters private final int servingSize; private final int servings; // Optional parameters - initialized to default values private int calories = 0; private int fat = 0; private int sodium = 0; private int carbohydrate = 0; public Builder(int servingSize, int servings) { this.servingSize = servingSize; this.servings = servings; } public Builder calories(int val){ calories = val; return this; } public Builder fat(int val){ fat = val; return this; } public Builder sodium(int val){ sodium = val; return this; } public Builder carbohydrate(int val){ carbohydrate = val; return this; } public NutritionFacts build() { return new NutritionFacts(this); } } private NutritionFacts(Builder builder) { servingSize = builder.servingSize; servings = builder.servings; calories = builder.calories; fat = builder.fat; sodium = builder.sodium; carbohydrate = builder.carbohydrate; } } // 使用 NutritionFacts cocaCola = new NutritionFacts.Builder(240,8) .calories(100) .sodium(35) .carbohydrate(27) .build();
public abstract class Pizza { public enum Topping { HAM, MUSHROOM, ONION, PEPPER,SAUSAGE } final Set<Topping> toppings; abstract static class Builder<T extends Builder<T>> { EnumSet<Topping> toppings = EnumSet.noneOf(Topping.class); public T addTopping(Topping topping) { toppings.add(Objects.requireNonNull(topping)); return self(); } abstract Pizza build(); protected abstract T self(); } Pizza(Builder<?> builder) { toppings = builder.toppings.clone(); // See Item 50 } } public class NyPizza extends Pizza { public enum Size { SMALL, MEDIUM, LARGE } private final Size size; public static class Builder extends Pizza.Builder<Builder> { private final Size size; public Builder(Size size) { this.size = Objects.requireNonNull(size); } public NyPizza build() { return new NyPizza(this); } protected Builder self() { return this; } } private NyPizza(Builder builder) { super(builder); size = builder.size; } } NyPizza pizza = new NyPizza.Builder(SMALL) .addTopping(SAUSAGE) .addTopping(ONION).build();
優點:數組
缺點:緩存
public class Elvis { public static final Elvis INSTANCE = new Elvis(); private Elvis() {} public void leaveTheBuilding() {} } public class Elvis { private static final Elvis INSTANCE = new Elvis(); private Elvis() {} public void leaveTheBuilding() {} public static Elvis instance(){ return INSTANCE; } }
public class Elvis { private Elvis() {} public void leaveTheBuilding() {} // 經過類加載機制來保證線程安全 private static class Holder{ private static final Elvis INSTANCE = new Elvis(); } public static Elvis instance(){ return Holder.INSTANCE; } }
public class Elvis { private Elvis() {} public void leaveTheBuilding() {} private static volatile Elvis INSTANCE; public static Elvis instance(){ if(INSTANCE == null){ synchronized(Elvis.class){ if (INSTANCE == null) { INSTANCE = new Elvis(); } } } return INSTANCE; } }
public enum Elvis { INSTANCE; public void leaveTheBuilding() {} }
第4種具有禁止反序列化建立對象問題安全
第1~3種若是實現了Serializable接口的補償措施架構
// 方法1 private static Class getClass(String classname) throws ClassNotFoundException { ClassLoader classLoader = Thread.currentThread().getContextClassLoader(); if(classLoader == null) classLoader = Singleton.class.getClassLoader(); return (classLoader.loadClass(classname)); } } // 方法2 // 重寫readReslove方法,須要將全部成員變量聲明爲transient private Object readResolve() { return INSTANCE; }
參考:併發
public class UtilityClass { // Suppress default constructor for noninstantiability private UtilityClass() { throw new AssertionError(); } // Remainder omitted }
靜態工具類和Singleton對於類行爲須要被底層資源參數化的場景是不適用的。ide
public class SpellChecker { private final Lexicon dictionary; // 所需的底層資源 public SpellChecker(Lexicon dictionary) { this.dictionary = Objects.requireNonNull(dictionary); } public boolean isValid(String word) { ... } public List<String> suggestions(String typo) { ... } }
public class SpellChecker{ private Lexicon dictionary; // 所需的底層資源 void setDictionary(Lexicon dictionary){ this.dictionary = dictionary; } public boolean isValid(String word) { ... } public List<String> suggestions(String typo) { ... } }
public interface DictionaryDependent{ void setDependence(Lexicon dictionary); } public class SpellChecker implement DictionaryDependent{ private Lexicon dictionary; // 所需的底層資源 void setDependence(Lexicon dictionary){ this.dictionary = dictionary; } public boolean isValid(String word) { ... } public List<String> suggestions(String typo) { ... } }
參考:工具
// 每次都生成Pattern對象,形成內存浪費 static boolean isRomanNumeral(String s) { return s.matches("^(?=.)M*(C[MD]|D?C{0,3})" + "(X[CL]|L?X{0,3})(I[XV]|V?I{0,3})$"); } public class RomanNumerals { private static final Pattern ROMAN = Pattern.compile("^(?=.)M*(C[MD]|D?C{0,3})" + "(X[CL]|L?X{0,3})(I[XV]|V?I{0,3})$"); static boolean isRomanNumeral(String s) { return ROMAN.matcher(s).matches(); } }
// 回收操做和把對象放入引用隊列由JVM處理,WeakHashMap只須要建立WeakReference時,把ReferenceQueue放入便可 // 同步操做:該方法被WeakHashMap中的全部操做涉及,表明只要進行操做就會進行同步,可能你會擔憂性能問題,可是實際上若是queue中沒有數據時,直接就返回了。 private void expungeStaleEntries() { // 循環清除queue中的元素 for (Object x; (x = queue.poll()) != null; ) { // 防止併發 synchronized (queue) { @SuppressWarnings("unchecked") Entry<K,V> e = (Entry<K,V>) x; int i = indexFor(e.hash, table.length); Entry<K,V> prev = table[i]; Entry<K,V> p = prev; while (p != null) { Entry<K,V> next = p.next; if (p == e) { if (prev == e) table[i] = next; else prev.next = next; // 協助GC操做,清除數組中的元素 e.value = null; // Help GC size--; break; } prev = p; p = next; } } } }
public class Room implements AutoCloseable { private static final Cleaner cleaner = Cleaner.create(); // Resource that requires cleaning. Must not refer to Room! private static class State implements Runnable { int numJunkPiles; // Number of junk piles in this room State(int numJunkPiles) { this.numJunkPiles = numJunkPiles; } // Invoked by close method or cleaner @Override public void run() { System.out.println("Cleaning room"); numJunkPiles = 0; } } // The state of this room, shared with our cleanable private final State state; // Our cleanable. Cleans the room when it’s eligible for gc private final Cleaner.Cleanable cleanable; public Room(int numJunkPiles) { state = new State(numJunkPiles); cleanable = cleaner.register(this, state); } @Override public void close() { cleanable.clean(); } }
static void copy(String src, String dst) throws IOException { InputStream in = new FileInputStream(src); try { OutputStream out = new FileOutputStream(dst); try { byte[] buf = new byte[BUFFER_SIZE]; int n; while ((n = in.read(buf)) >= 0) out.write(buf, 0, n); } finally { out.close(); } } finally { in.close(); } }
static void copy(String src, String dst) throws IOException { try ( InputStream in = new FileInputStream(src); OutputStream out = new FileOutputStream(dst) ) { byte[] buf = new byte[BUFFER_SIZE]; int n; while ((n = in.read(buf)) >= 0) out.write(buf, 0, n); } }