java编程思想读书笔记
多態(tài)
任何域的訪問操作都將有編譯器解析,如果某個(gè)方法是靜態(tài)的,它的行為就不具有多態(tài)性
java默認(rèn)對象的銷毀順序與初始化順序相反
編寫構(gòu)造器時(shí)有一條有效的準(zhǔn)則:“盡可能用簡單的方法使對象進(jìn)入正常狀態(tài),如果可以的話,避免調(diào)用其他方法”,下面的實(shí)例說明
//: polymorphism/PolyConstructors.java // Constructors and polymorphism // don't produce what you might expect. import static net.mindview.util.Print.*;class Glyph { void draw() { print("Glyph.draw()"); } Glyph() {print("Glyph() before dr aw()");draw();//invoke RoundGlyph.draw(),this is because that 后期綁定print("Glyph() after draw()"); } } class RoundGlyph extends Glyph { private int radius = 1; RoundGlyph(int r) {radius = r;print("RoundGlyph.RoundGlyph(), radius = " + radius); } void draw() {print("RoundGlyph.draw(), radius = " + radius); } } public class PolyConstructors { public static void main(String[] args) {new RoundGlyph(5); } } /* Output: Glyph() before draw() RoundGlyph.draw(), radius = 0 Glyph() after draw() RoundGlyph.RoundGlyph(), radius = 5 *///:~向上轉(zhuǎn)型(在繼承層次中向上轉(zhuǎn)型)會(huì)丟失東西,對應(yīng)于窄化轉(zhuǎn)換,會(huì)丟失一些信息,這個(gè)主要丟失的是類型信息。向上轉(zhuǎn)型是安全的(這里跟窄化轉(zhuǎn)換相反,可以思考下為什么?)因?yàn)榛惤涌谛∮诘扔趯?dǎo)出類接口的。
有時(shí)候組合模式能夠使我們在運(yùn)行期間獲得動(dòng)態(tài)靈活性(狀態(tài)模式),如下面代碼所示
//: polymorphism/Transmogrify.java // Dynamically changing the behavior of an object // via composition (the "State" design pattern). import static net.mindview.util.Print.*;class Actor { public void act() {} }class HappyActor extends Actor { public void act() { print("HappyActor"); } }class SadActor extends Actor { public void act() { print("SadActor"); } }class Stage { private Actor actor = new HappyActor(); public void change() { actor = new SadActor(); }//this show that dynamic flexibility public void performPlay() { actor.act(); } }public class Transmogrify { public static void main(String[] args) {Stage stage = new Stage();stage.performPlay();stage.change();stage.performPlay(); } } /* Output: HappyActor SadActor *///:~is a關(guān)系可以采用繼承的方式,has a關(guān)系采用組合的方式
接口
(理解不了的句子打?,下同)接口和內(nèi)部類為我們提供了中將接口與實(shí)現(xiàn)分離的更加結(jié)構(gòu)化的方法
(?)抽象類是普通類與接口之間的中庸之道
創(chuàng)建一個(gè)不含任何抽象方法的抽象類的意義在于有個(gè)類想要阻止用戶產(chǎn)生該類的實(shí)例且方法中沒有用abstract的必要。
(?)interface關(guān)鍵字使抽象類的概念更向前邁進(jìn)一步,可以將它的作用說成是建立類與類之間的協(xié)議
接口也可以包含域(變量,實(shí)例),但是在底層隱式的是static和final
兩者關(guān)系如果感覺是超級抽象(至少通過名字是感受不出來有關(guān)系),但是有微弱的聯(lián)系,就可以用接口
使用接口的核心原因是:單個(gè)類能夠向上轉(zhuǎn)型為多個(gè)基類型,第二個(gè)原因是與抽象基類使用的原因相同,不允許用戶創(chuàng)建該類的對象(抽象基類和接口不允許new)。
如果知道某事物應(yīng)該成為一個(gè)基類,那么第一選擇應(yīng)該是使它成為一個(gè)接口
不要在不同的接口中使用相同的方法名
(?)策略模式,適配器模式(需要總結(jié)),這兩種模式利用接口實(shí)現(xiàn),概述如下(以Scanner為例):
public interface Readable {/*** Attempts to read characters into the specified character buffer.* The buffer is used as a repository of characters as-is: the only* changes made are the results of a put operation. No flipping or* rewinding of the buffer is performed.** @param cb the buffer to read characters into* @return The number of {@code char} values added to the buffer,* or -1 if this source of characters is at its end* @throws IOException if an I/O error occurs* @throws NullPointerException if cb is null* @throws java.nio.ReadOnlyBufferException if cb is a read only buffer*/public int read(java.nio.CharBuffer cb) throws IOException;}/**Readable is interface,we can use any class that implement the Readable as the construtor's parameter*/public Scanner(Readable source) {this(Objects.requireNonNull(source, "source"), WHITESPACE_PATTERN);}- 之前可以用interface創(chuàng)建具有static, final類型的常量,現(xiàn)在用enum
- 接口在工廠設(shè)計(jì)模式上的應(yīng)用,使用匿名內(nèi)部類實(shí)現(xiàn)的工廠模式
- 一個(gè)類大多數(shù)情況下相當(dāng)于接口和工廠
內(nèi)部類
它允許你把一些邏輯相關(guān)的類組織在一起,并控制位于內(nèi)部的類的可視性,內(nèi)部類寫出的代碼更加優(yōu)雅而清晰,盡管并不總是這樣
內(nèi)部類能訪問其外圍對象的所有成員,用該性質(zhì)可以實(shí)現(xiàn)迭代器設(shè)計(jì)模式
package com.innerclass;import java.util.Iterator;interface Selector { boolean end(); Object current(); void next(); } public class Sequence { private Object[] items; private int next = 0; public Sequence(int size) { items = new Object[size]; } public void add(Object x) {if(next < items.length)items[next++] = x; }//innerClass that implements Selector,it can use any objects of outerClass private class SequenceSelector implements Selector {private int i = 0;public boolean end() { return i == items.length; }//access items of outerClasspublic Object current() { return items[i]; }public void next() { if(i < items.length) i++; } } public Selector selector() {return new SequenceSelector(); } public static void main(String[] args) {Sequence sequence = new Sequence(10);for(int i = 0; i < 10; i++)sequence.add(Integer.toString(i));Selector selector = sequence.selector();//while(!selector.end()) {System.out.print(selector.current() + " ");selector.next();} } } /* Output: 0 1 2 3 4 5 6 7 8 9 *///:~并且我們可以看到在java源碼中ArrayList的迭代器的實(shí)現(xiàn)也是采用類似的方法
內(nèi)部類new的方法:DotNew dn = new DotNew();DotNew.Inner dni = dn.new Inner()
內(nèi)部類可以更靈活的進(jìn)行權(quán)限的控制,比如:某個(gè)類可以訪問,但其他類不能訪問,就可以用private關(guān)鍵字去實(shí)現(xiàn)
10.5略過
匿名內(nèi)部類,解釋代碼如下:
package com.innerclass;//: innerclasses/Parcel7.java and Contents.java // Returning an instance of an anonymous inner class.public class Parcel7 { public interface Contents {int value();} ///:~public Contents contents() { //匿名內(nèi)部類的現(xiàn)象return new Contents() { // auto implements Contentsprivate int i = 11;public int value() { return i; }}; // Semicolon required in this case } public static void main(String[] args) {Parcel7 p = new Parcel7();Contents c = p.contents(); } } ///:~其可以用來優(yōu)化工廠設(shè)計(jì)模式,代碼如下:
package com.innerclass; interface Service { void method1(); void method2(); } interface ServiceFactory { Service getService(); } class Implementation1 implements Service { private Implementation1() {} public void method1() {System.out.println("Implementation1 method1");} public void method2() {System.out.println("Implementation1 method2");} public static ServiceFactory factory =new ServiceFactory() {public Service getService() {return new Implementation1();}}; } class Implementation2 implements Service { private Implementation2() {} public void method1() {System.out.println("Implementation2 method1");} public void method2() {System.out.println("Implementation2 method2");} //匿名內(nèi)部類,可以直接引用變量,static是為了保證單一的工廠對象 public static ServiceFactory factory =new ServiceFactory() {public Service getService() {return new Implementation2();}}; } public class Factories { public static void serviceConsumer(ServiceFactory fact) {Service s = fact.getService();s.method1();s.method2(); } public static void main(String[] args) {serviceConsumer(Implementation1.factory);// Implementations are completely interchangeable:serviceConsumer(Implementation2.factory); } } /* Output: Implementation1 method1 Implementation1 method2 Implementation2 method1 Implementation2 method2 *///:~嵌套類就是在內(nèi)部類基礎(chǔ)上前面加個(gè)static關(guān)鍵字,通過static關(guān)鍵字能得到嵌套類的幾個(gè)性質(zhì):
1.要?jiǎng)?chuàng)建嵌套類的對象,并不需要其外圍類的對象
? 2.不能從嵌套類的對象中訪問非靜態(tài)的外圍類對象寫測試類代碼的時(shí)候,可以用嵌套類如下這種方式,這樣就可以只用寫一個(gè)main了,代碼如下:
package com.innerclass;//: innerclasses/TestBed.java // Putting test code in a nested class. // {main: TestBed$Tester}public class TestBed { public void f() { System.out.println("f()"); } public static class Tester {public static void main(String[] args) {Factories f = new Factories();Tester t = new Tester();//此處不用new TestBed.Tester();TestBed t = new TestBed();t.f();} } } /* Output: f() *///:~為什么要使用內(nèi)部類:
//: innerclasses/MultiImplementation.java // With concrete or abstract classes, inner // classes are the only way to produce the effect // of "multiple implementation inheritance." package innerclasses;class D {} abstract class E {}class Z extends D { E makeE() { return new E() {}; } }public class MultiImplementation { static void takesD(D d) {} static void takesE(E e) {} public static void main(String[] args) {Z z = new Z();takesD(z);takesE(z.makeE()); } } ///:~
1.當(dāng)擁有抽象類或者具體類的時(shí)候,我們只能用內(nèi)部類實(shí)現(xiàn)多重繼承,代碼如下????2.創(chuàng)建內(nèi)部類后,使用變量是比較靈活,方便的,通過迭代器模式就能夠看出來
(?)閉包,lambda表達(dá)式與回調(diào)
package com.innerclass;//: innerclasses/Callbacks.java // Using inner classes for callbacksinterface Incrementable { void increment(); }// Very simple to just implement the interface: class Callee1 implements Incrementable { private int i = 0; public void increment() {i++;System.out.println(i); } } class MyIncrement { public void increment() { System.out.println("Other operation"); } static void f(MyIncrement mi) { mi.increment(); } } // If your class must implement increment() in // some other way, you must use an inner class: class Callee2 extends MyIncrement { private int i = 0; public void increment() {super.increment();i++;System.out.println(i); } private class Closure implements Incrementable {public void increment() {// Specify outer-class method, otherwise// you'd get an infinite recursion:Callee2.this.increment();System.out.println("closure");} } Incrementable getCallbackReference() {return new Closure(); } } class Caller { private Incrementable callbackReference; Caller(Incrementable cbh) { callbackReference = cbh; } void go() { callbackReference.increment(); System.out.println("go");}//調(diào)用了匿名內(nèi)部類的函數(shù) }public class Callbacks { public static void main(String[] args) {Callee2 c2 = new Callee2();MyIncrement.f(c2);//以匿名內(nèi)部類實(shí)現(xiàn)的回調(diào)new Caller(new Incrementable() {//callback the function@Overridepublic void increment() {// TODO Auto-generated method stubSystem.out.println("callback");} }).go();//以非匿名類內(nèi)部類回調(diào)new Caller(c2.getCallbackReference()).go(); } }
閉包可以理解為匿名內(nèi)部類就可以了,其跟lambda表達(dá)式的定義和演算相關(guān),回調(diào)是基于內(nèi)部類實(shí)現(xiàn)的,代碼如下:(?需要體悟)設(shè)計(jì)模式總是將變化的事務(wù)與保持不變的事務(wù)分離開
(?需要感悟)內(nèi)部類是很像多重繼承的,多重繼承可以使用其父類的public后者protected變量,而內(nèi)部類也可以這樣。闡述代碼如下:
public class GreenhouseControls extends Controller { private boolean light = false; public class LightOn extends Event {public LightOn(long delayTime) { super(delayTime); }public void action() {// Put hardware control code here to// physically turn on the light.light = true;}public String toString() { return "Light is on"; } } // public class LightOff extends Event {public LightOff(long delayTime) { super(delayTime); }public void action() {// Put hardware control code here to// physically turn off the light.light = false;}public String toString() { return "Light is off"; } } }相當(dāng)于extends Controller, Event盡管java沒有這樣的語法,也就是說當(dāng)你感覺需要繼承多個(gè)類的時(shí)候,不防試一試內(nèi)部類。
(?有點(diǎn)難和偏)內(nèi)部類的繼承,內(nèi)部類方法可以被覆蓋嗎?
- (?自己的問題)接口和內(nèi)部類跟c++虛函數(shù)和純虛函數(shù)的關(guān)系?
- 這些特性的使用應(yīng)該是在設(shè)計(jì)階段就能夠確定的問題。
持有對象
該主題解決的問題是運(yùn)行時(shí)(動(dòng)態(tài)決定)決定持有對象的數(shù)量甚至類型,提出容器類的概念。
基本類型是存儲(chǔ)在堆棧中,其要求聲明size。
比較詳細(xì)的解釋了容器類,更詳細(xì)的還在后面
Collection:獨(dú)立的元素序列,Map:由鍵值對組成的對象,可以通過鍵來查找值。
(誤區(qū)),代碼闡述如下
public static void main(String[] args){Base b = new Sub();List<String> list = new ArrayList<>();//[1]List<String> list2 = new LinkedList<>();//[2]LinkedList<String> list3 = new LinkedList<>();//[3]}[2]中的list2只能d調(diào)用List中實(shí)現(xiàn)的函數(shù)和LinkedList實(shí)現(xiàn)函數(shù)的交集而[3]中的list3同理
字符串
每一個(gè)修改String的值,在內(nèi)部實(shí)現(xiàn)中都是創(chuàng)建過一個(gè)或者多個(gè)String對象,而最初的String對象則絲毫未動(dòng)
如果toString方法比較簡單(toString(){}就是說將Object->String)就可以用+,編譯器可以自動(dòng)優(yōu)化為StringBuilder的方式,但是如果在toString上有循環(huán)你就有必要表明StringBuilder sb = new StringBuilder();,而不能去指望編譯器的優(yōu)化。
StringBuffer是線程安全的,而StringBuilder不是。
打印內(nèi)存地址不能用this,應(yīng)該用Object.toString(),解釋如下
package com.string; import java.util.*;public class InfiniteRecursion { //this->String對象,就會(huì)調(diào)用this.toString(),于是就發(fā)生了無意識遞歸 public String toString() {return " InfiniteRecursion address: " + this + "\n"; } public static void main(String[] args) {List<InfiniteRecursion> v =new ArrayList<InfiniteRecursion>();for(int i = 0; i < 10; i++)v.add(new InfiniteRecursion());System.out.println(v);//println()->InfiniteRecursion.toString(); } } ///:輸出異常格式化輸出:System.out.format("row 1: [%d %f]",x ,y),跟C語言的printf()一樣的理解
String轉(zhuǎn)為2,4,6,8,16進(jìn)制經(jīng)常會(huì)用到String.format()
正則表達(dá)式
- 正則表達(dá)式用于split,可以看到正則表達(dá)式匹配的那一部分都不存在了
- 正則表達(dá)式用于替換
- Matcher和Pattern:m.find()相當(dāng)于next()返回bool型,其有個(gè)重載的m.find(i)表示從index = i的地方開始查找匹配的子串,m.group()返回當(dāng)前匹配到的字符串,m.start() 和m.end()表示匹配到的子串在原父串的起始,末尾的索引。
RTTI(類型信息)
含義:在運(yùn)行時(shí),識別一個(gè)對象的類型。代碼解釋如下:
//: typeinfo/Shapes.javaimport java.util.*;abstract class Shape {void draw() { System.out.println(this + ".draw()"); }abstract public String toString();}class Circle extends Shape {public String toString() { return "Circle"; }}class Square extends Shape {public String toString() { return "Square"; }}class Triangle extends Shape {public String toString() { return "Triangle"; }} public class Shapes {public static void main(String[] args) {List<Shape> shapeList = Arrays.asList(new Circle(), new Square(), new Triangle());for(Shape shape : shapeList)shape.draw();}} /* Output:Circle.draw()Square.draw()Triangle.draw()*///:~在編譯時(shí),具體形狀都向上轉(zhuǎn)型為Shape類型了,方法也只能調(diào)用Shape類的方法,但在運(yùn)行時(shí),可以識別出具體的類型信息。
java程序在它開始運(yùn)行之前并非完全加載,與C++這樣的靜態(tài)加載語言不同,比如Class.forName()這種方法能夠體現(xiàn)出其特點(diǎn)
用.class形式去創(chuàng)建對象引用時(shí),不會(huì)像class.forName()去自動(dòng)初始化Class對象,代碼解釋如下:
package com.typeinfo;import java.util.*;class Initable {static final int staticFinal = 47;static final int staticFinal2 =ClassInitialization.rand.nextInt(1000);static {System.out.println("Initializing Initable");}public void name() {System.out.println("name() is invoked");}}class Initable2 {static int staticNonFinal = 147;static {System.out.println("Initializing Initable2");}}class Initable3 {static int staticNonFinal = 74;static {System.out.println("Initializing Initable3");}}public class ClassInitialization {public static Random rand = new Random(47);public static void main(String[] args) throws Exception {// Class initable = Initable.class;//泛型語法形式,盡量使用泛化的形式// Class<Initable> initable = Initable.class;//泛型語法形式,盡量使用泛化的形式// Class<?> initable = Initable.class;//泛型語法形式,盡量使用泛化的形式Class<? extends Object> initable = Initable.class;//泛型語法形式,盡量使用泛化的形式Initable.class.newInstance().name();//實(shí)例調(diào)用,即初始化該Class對象且將對象實(shí)例化了System.out.println("After creating Initable ref");// Does not trigger initialization:System.out.println(Initable.staticFinal);// Does trigger initialization:System.out.println(Initable.staticFinal2);// Does trigger initialization:System.out.println(Initable2.staticNonFinal);Class initable3 = Class.forName("com.typeinfo.Initable3");//只初始化了Class對象,并沒有實(shí)例化System.out.println("After creating Initable3 ref");System.out.println(Initable3.staticNonFinal);}} /* Output:Initializing Initablename() is invokedAfter creating Initable ref47258Initializing Initable2147Initializing Initable3After creating Initable3 ref74*///:~泛型語法和RTTI的原理結(jié)合起來可以做出很多解耦和的事情,使代碼更加清晰漂亮,如下
package com.typeinfo;import java.util.*;class CountedInteger {private static long counter;public final long id = counter++;public String toString() { return Long.toString(id); }}public class FilledList<T> {private Class<T> type;public FilledList(Class<T> type) { this.type = type; } public List<T> create(T[] ts){List<T> result = new ArrayList<T>();for(T t : ts){result.add(t);}return result; }public List<T> create(int nElements) {List<T> result = new ArrayList<T>();try {for(int i = 0; i < nElements; i++)result.add(type.newInstance());//1.返回該對象的確切類型} catch(Exception e) {throw new RuntimeException(e);}return result;}public static void main(String[] args) {List<CountedInteger> l = new ArrayList<CountedInteger>();CountedInteger[] cis = new CountedInteger[15];//空引用,相當(dāng)于先給定了一個(gè)空間for(int i = 0; i < 15; i++){cis[i] = new CountedInteger();}FilledList<CountedInteger> fl =new FilledList<CountedInteger>(CountedInteger.class);System.out.println("create1:" + fl.create(15));System.out.println("create2:" + fl.create(cis));}} /* Output:create1:[15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29]create2:[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14]*///:~在代碼中type.newInstance()產(chǎn)生的是確定的類型,因?yàn)榭梢员硎龀?lt;? extends Object>,(?)這在某些程度上有些受限,下面代碼因?yàn)?lt;? super FancyToy>的存在,返回的是Object類型,代碼如下:
package com.typeinfo;//: typeinfo/toys/GenericToyTest.java// Testing class Class.public class GenericToyTest {public static void main(String[] args) throws Exception {Class<FancyToy> ftClass = FancyToy.class;// Produces exact type:FancyToy fancyToy = ftClass.newInstance();Class<? super FancyToy> up = ftClass.getSuperclass();// This won't compile:// Class<Toy> up2 = ftClass.getSuperclass();// Only produces Object:Object obj = up.newInstance();}} ///:~向下轉(zhuǎn)型需要使用顯示的類型轉(zhuǎn)換如Cicle c = (Cicle)new Shape()。
instanceof即檢查某個(gè)對象的實(shí)例是否屬于某個(gè)類或接口可以簡潔的記為一個(gè) <實(shí)例,類|接口>,如果程序中編寫了許多的instanceof表達(dá)式,就說明你的設(shè)計(jì)可能存在瑕疵,下面以一個(gè)例子說明instanceof的用法,以及里面涉及到模板設(shè)計(jì)模式,思考在ForNameCreator.java中為什么要用Class去包裹即Class<? extends Pet>而不直接用<? extends Pet>
//: typeinfo/pets/Cat.javapackage com.typeinfo.pets;public class Cat extends Pet {public Cat(String name) { super(name); }public Cat() { super(); }} ///:~//若干繼承Pet的動(dòng)物,這里省略//... //: typeinfo/pets/ForNameCreator.javapackage com.typeinfo.pets;import java.util.*;public class ForNameCreator extends PetCreator {//表示了一個(gè)不確定且是Pet的導(dǎo)出類的類型的List,相當(dāng)于對類型的范圍進(jìn)行了指定,可以強(qiáng)制讓編譯器執(zhí)行類型檢查,想一想為什么要加Class包裹rivate static List<Class<? extends Pet>> types = new ArrayList<Class<? extends Pet>>();//和上面的解釋是一樣的,但其不能添加元素,涉及到模板的知識(?)static List<? extends Pet> typ = new ArrayList<>();static Map<Person,List<? extends Pet>> petPeple = new HashMap<Person,List<? extends Pet>>();static List<Dog> pets = new ArrayList<>();// Types that you want to be randomly created:private static String[] typeNames = { "com.typeinfo.pets.Mutt","com.typeinfo.pets.Pug","com.typeinfo.pets.EgyptianMau","com.typeinfo.pets.Manx","com.typeinfo.pets.Cymric","com.typeinfo.pets.Rat","com.typeinfo.pets.Mouse","com.typeinfo.pets.Hamster"}; @SuppressWarnings("unchecked")private static void loader() {petPeple.put(new Person("d"), pets); try {for(String name : typeNames){Class<? extends Pet> c = (Class<? extends Pet>) Class.forName(name) ; // typ.add(c.newInstance());error,can not run addtypes.add((Class<? extends Pet>)Class.forName(name));//進(jìn)行了類型轉(zhuǎn)換,是什么確定的類型都有可能,在運(yùn)行時(shí)確定,這就是RTTI內(nèi)容之一}} catch(ClassNotFoundException e) {throw new RuntimeException(e);}}static { loader(); }//直接在new ForNameCreator()中執(zhí)行l(wèi)oader(),或者直接在構(gòu)造器中調(diào)用loader()public List<Class<? extends Pet>> types() {return types;}} ///:~ //: typeinfo/pets/PetCreator.java// Creates random sequences of Pets.package com.typeinfo.pets;import java.util.*;public abstract class PetCreator {private Random rand = new Random(47);// The List of the different types of Pet to createpublic abstract List<Class<? extends Pet>> types();public Pet randomPet() { // Create one random Petint n = rand.nextInt(types().size());try {return types().get(n).newInstance();//產(chǎn)生了確切的實(shí)例,因?yàn)?lt;? extends Pet>} catch(InstantiationException e) {throw new RuntimeException(e);} catch(IllegalAccessException e) {throw new RuntimeException(e);}} public Pet[] createArray(int size) {Pet[] result = new Pet[size];for(int i = 0; i < size; i++)result[i] = randomPet();return result;}public ArrayList<Pet> arrayList(int size) {ArrayList<Pet> result = new ArrayList<Pet>();Collections.addAll(result, createArray(size));return result;}} ///:~ package com.typeinfo;// Using instanceof.import java.util.*;import com.typeinfo.pets.*;public class PetCount {static class PetCounter extends HashMap<String,Integer> {public void count(String type) {Integer quantity = get(type);if(quantity == null)put(type, 1);elseput(type, quantity + 1);}} public static voidcountPets(PetCreator creator) {PetCounter counter= new PetCounter();for(Pet pet : creator.createArray(20)) {// List each individual pet:System.out.println(pet.getClass().getSimpleName() + " ");if(pet instanceof Pet)counter.count("Pet");if(pet instanceof Dog)counter.count("Dog");if(pet instanceof Mutt)counter.count("Mutt");if(pet instanceof Pug)counter.count("Pug");if(pet instanceof Cat)counter.count("Cat");if(pet instanceof Manx)counter.count("EgyptianMau");if(pet instanceof Manx)counter.count("Manx");if(pet instanceof Manx)counter.count("Cymric");if(pet instanceof Rodent)counter.count("Rodent");if(pet instanceof Rat)counter.count("Rat");if(pet instanceof Mouse)counter.count("Mouse");if(pet instanceof Hamster)counter.count("Hamster");}// Show the counts:System.out.println();System.out.println(counter);} public static void main(String[] args) {countPets(new ForNameCreator());}} /* Output:Rat Manx Cymric Mutt Pug Cymric Pug Manx Cymric Rat EgyptianMau Hamster EgyptianMau Mutt Mutt Cymric Mouse Pug Mouse Cymric{Pug=3, Cat=9, Hamster=1, Cymric=7, Mouse=2, Mutt=3, Rodent=5, Pet=20, Manx=7, EgyptianMau=7, Dog=6, Rat=2}*///:~ 用動(dòng)態(tài)的`instanceof`即isInstance()去計(jì)數(shù),該計(jì)數(shù)的原理如下圖:ABCDEF B C B C A D 找出第二列出現(xiàn)B的次數(shù),因?yàn)锽CAD全都繼承于Pet,所以要用isInstance()去判定是否 屬于某個(gè)具體類型
//: typeinfo/PetCount3.java// Using isInstance()import typeinfo.pets.*;import java.util.*;import net.mindview.util.*;import static net.mindview.util.Print.*;public class PetCount3 {static class PetCounterextends LinkedHashMap<Class<? extends Pet>,Integer> {public PetCounter() {super(MapData.map(LiteralPetCreator.allTypes, 0));}public void count(Pet pet) {// Class.isInstance() eliminates instanceofs:for(Map.Entry<Class<? extends Pet>,Integer> pair: this.entrySet())if(pair.getKey().isInstance(pet))put(pair.getKey(), pair.getValue() + 1);} public String toString() {StringBuilder result = new StringBuilder("{");for(Map.Entry<Class<? extends Pet>,Integer> pair: entrySet()) {result.append(pair.getKey().getSimpleName());result.append("=");result.append(pair.getValue());result.append(", ");}result.delete(result.length()-2, result.length());result.append("}");return result.toString();}} public static void main(String[] args) {PetCounter petCount = new PetCounter();for(Pet pet : Pets.createArray(20)) {printnb(pet.getClass().getSimpleName() + " ");petCount.count(pet);}print();print(petCount);}} /* Output:Rat Manx Cymric Mutt Pug Cymric Pug Manx Cymric Rat EgyptianMau Hamster EgyptianMau Mutt Mutt Cymric Mouse Pug Mouse Cymric{Pet=20, Dog=6, Cat=9, Rodent=5, Mutt=3, Pug=3, EgyptianMau=2, Manx=7, Cymric=5, Rat=2, Mouse=2, Hamster=1}*///:~還可以用Class.isAssignableFrom()來計(jì)數(shù),其是用來判斷一個(gè)類Class1和另一個(gè)類Class2是否相同或是另一個(gè)類的超類或接口。下面代碼對基類型和確切類型都進(jìn)行了計(jì)數(shù)比如當(dāng)遍歷到dog的時(shí)候,dog的count++,pet的count++:
package net.mindview.util;import java.util.*;public class TypeCounter extends HashMap<Class<?>,Integer>{private Class<?> baseType;public TypeCounter(Class<?> baseType) {this.baseType = baseType;}public void count(Object obj) {Class<?> type = obj.getClass();if(!baseType.isAssignableFrom(type))throw new RuntimeException(obj + " incorrect type: "type + ", should be type or subtype of "baseType);countClass(type);} private void countClass(Class<?> type) {Integer quantity = get(type);put(type, quantity == null ? 1 : quantity + 1);Class<?> superClass = type.getSuperclass();if(superClass != null &&baseType.isAssignableFrom(superClass))countClass(superClass);}public String toString() {StringBuilder result = new StringBuilder("{");for(Map.Entry<Class<?>,Integer> pair : entrySet()) {result.append(pair.getKey().getSimpleName());result.append("=");result.append(pair.getValue());result.append(", ");}result.delete(result.length()-2, result.length());result.append("}");return result.toString();}} ///:~ //: typeinfo/PetCount4.javaimport typeinfo.pets.*;import net.mindview.util.*;import static net.mindview.util.Print.*;public class PetCount4 {public static void main(String[] args) {TypeCounter counter = new TypeCounter(Pet.class);for(Pet pet : Pets.createArray(20)) {printnb(pet.getClass().getSimpleName() + " ");counter.count(pet);}print();print(counter);}} /* Output: (Sample)Rat Manx Cymric Mutt Pug Cymric Pug Manx Cymric Rat EgyptianMau Hamster EgyptianMau Mutt Mutt Cymric Mouse Pug Mouse Cymric{Mouse=2, Dog=6, Manx=7, EgyptianMau=2, Rodent=5, Pug=3, Mutt=3, Cymric=5, Cat=9, Hamster=1, Pet=20, Rat=2}*///:~注冊工廠,可以用模板的方法+構(gòu)造器的方式,結(jié)合上面所講可以用newInstance去代替構(gòu)造器,兩種方法如下
package com.typeinfo;//: typeinfo/RegisteredFactories.java// Registering Class Factories in the base class.import java.util.*;import com.typeinfo.Factory;interface Factory<T> { T create(); } ///:~class Part {/*** 模板+RTTI方法*/public String toString() {return getClass().getSimpleName();}static List<Class<? extends Part>> partClasses = new ArrayList<Class<? extends Part>>();static {//創(chuàng)建類字面變量,利用newInstance()方法使其不用再類里面顯示調(diào)用構(gòu)造器partClasses.add(FuelFilter.class);partClasses.add(AirFilter.class);partClasses.add(CabinAirFilter.class);partClasses.add(OilFilter.class);partClasses.add(FanBelt.class);partClasses.add(PowerSteeringBelt.class);partClasses.add(GeneratorBelt.class);}private static Random rand = new Random();public static Part createRandom() {int n = rand.nextInt(partClasses.size());try {return partClasses.get(n).newInstance();} catch(InstantiationException e) {throw new RuntimeException(e);} catch(IllegalAccessException e) {throw new RuntimeException(e);}} /*** 模板+構(gòu)造器方法*/// public String toString() {// return getClass().getSimpleName();// }// static List<Factory<? extends Part>> partFactories =// new ArrayList<Factory<? extends Part>>(); // static {// // Collections.addAll() gives an "unchecked generic// // array creation ... for varargs parameter" warning.// partFactories.add(new FuelFilter.Factory());// partFactories.add(new AirFilter.Factory());// partFactories.add(new CabinAirFilter.Factory());// partFactories.add(new OilFilter.Factory());// partFactories.add(new FanBelt.Factory());// partFactories.add(new PowerSteeringBelt.Factory());// partFactories.add(new GeneratorBelt.Factory());// }// private static Random rand = new Random(47);// public static Part createRandom() {// int n = rand.nextInt(partFactories.size());// return partFactories.get(n).create();// }} class Filter extends Part {}class FuelFilter extends Filter {// Create a Class Factory for each specific type:public static class Factoryimplements com.typeinfo.Factory<FuelFilter> {public FuelFilter create() { return new FuelFilter(); }}}class AirFilter extends Filter {public static class Factoryimplements com.typeinfo.Factory<AirFilter> {public AirFilter create() { return new AirFilter(); }}} class CabinAirFilter extends Filter {public static class Factoryimplements com.typeinfo.Factory<CabinAirFilter>{public CabinAirFilter create() {return new CabinAirFilter();}}}class OilFilter extends Filter {public static class Factoryimplements com.typeinfo.Factory<OilFilter> {public OilFilter create() { return new OilFilter(); }}} class Belt extends Part {}class FanBelt extends Belt {public static class Factoryimplements com.typeinfo.Factory<FanBelt> {public FanBelt create() { return new FanBelt(); }}}class GeneratorBelt extends Belt {public static class Factoryimplements com.typeinfo.Factory<GeneratorBelt> {public GeneratorBelt create() {return new GeneratorBelt();}}} class PowerSteeringBelt extends Belt {public static class Factoryimplements com.typeinfo.Factory<PowerSteeringBelt> {public PowerSteeringBelt create() {return new PowerSteeringBelt();}}} public class RegisteredFactories {public static void main(String[] args) {for(int i = 0; i < 10; i++)System.out.println(Part.createRandom());}} /* Output:GeneratorBeltCabinAirFilterGeneratorBeltAirFilterPowerSteeringBeltCabinAirFilterFuelFilterPowerSteeringBeltPowerSteeringBeltFuelFilter*///:~- 反射其中之一的功能是在運(yùn)行時(shí)創(chuàng)建類,但是其在運(yùn)行時(shí)也必須要有.class文件(提前設(shè)置在本地或者網(wǎng)絡(luò)),所以它和RTTI的核心的區(qū)別只在于一個(gè)在運(yùn)行時(shí)需要.calss文件,一個(gè)在編譯時(shí)需要.class文件
在反射中一般用到的并不是運(yùn)行時(shí)創(chuàng)建類,而是利用forName()得到的一個(gè)未可知的對象在運(yùn)行時(shí)進(jìn)行方法調(diào)用,其常用的方法有g(shù)etMethods(),getDeclaredMethod(),invoke(),getConstructors(),下面代碼給出了實(shí)例:
public class TestRef {public staticvoid main(String args[]) throws NoSuchMethodException, IllegalAccessException, InvocationTargetException {Foo foo = new Foo("這個(gè)一個(gè)Foo對象!");Class clazz = foo.getClass(); Method m1 = clazz.getDeclaredMethod("outInfo");Method m2 = clazz.getDeclaredMethod("setMsg", String.class);Method m3 = clazz.getDeclaredMethod("getMsg");m1.invoke(foo); m2.invoke(foo, "重新設(shè)置msg信息!"); String msg = (String) m3.invoke(foo); System.out.println(msg); } } class Foo { private String msg; public Foo(String msg) { this.msg = msg; } public void setMsg(String msg) {this.msg = msg; } public String getMsg() { return msg; } public void outInfo() {System.out.println("這是測試Java反射的測試類"); } }代理模式是基本的設(shè)計(jì)模式之一,代理通常充當(dāng)著中間人的作用,其具體分為靜態(tài)代理與動(dòng)態(tài)代理,靜態(tài)代理很簡單,代碼如下:
package com.typeinfo;//: typeinfo/SimpleProxyDemo.javainterface Interface {void doSomething();void somethingElse(String arg);void doLastThing();}class RealObject implements Interface {public void doSomething() { System.out.println("doSomething"); }public void somethingElse(String arg) {System.out.println("somethingElse " + arg);}public void doLastThing(){System.out.println("doLastThing");}} class SimpleProxy implements Interface {private Interface proxied;public SimpleProxy(Interface proxied) {this.proxied = proxied;}public void doSomething() {System.out.println("SimpleProxy doSomething");proxied.doSomething();}public void somethingElse(String arg) {System.out.println("SimpleProxy somethingElse " + arg);proxied.somethingElse(arg);}@Overridepublic void doLastThing() {// TODO Auto-generated method stub}} class SimpleProxyDemo {public static void consumer(Interface iface) {iface.doSomething();iface.somethingElse("bonobo");}public static void main(String[] args) {consumer(new RealObject());consumer(new SimpleProxy(new RealObject()));}} /* Output:doSomethingsomethingElse bonoboSimpleProxy doSomethingdoSomethingSimpleProxy somethingElse bonobosomethingElse bonobo*///:~而動(dòng)態(tài)代理是指代理類在程序運(yùn)行前不存在、運(yùn)行時(shí)由程序動(dòng)態(tài)生成的代理方式,即proxy代碼在運(yùn)行時(shí),jvm動(dòng)態(tài)產(chǎn)生代理類(proxy)代碼,因?yàn)槭褂梅瓷浜蚏TTI的特性,所以在性能上存在缺陷,通常代理模式用于java web而不用于前端,如Spring中大量使用代理模式,我們稱之為AOP(面向切面編程)。但是在代碼結(jié)構(gòu)和耦合性來看具有無可比擬的優(yōu)勢。動(dòng)態(tài)代理的簡單代碼如下
package com.typeinfo;//: typeinfo/SimpleDynamicProxy.javaimport java.lang.reflect.*;class DynamicProxyHandler implements InvocationHandler {private Object proxied;public DynamicProxyHandler(Object proxied) {this.proxied = proxied;}public Objectinvoke(Object proxy, Method method, Object[] args)throws Throwable {System.out.println("**** proxy: " + proxy.getClass() +", method: " + method + ", args: " + args);//可以過濾方法if(method.getName().equals("doLastThing")){return null;}if(args != null)for(Object arg : args)System.out.println(" " + arg);return method.invoke(proxied, args);}} class SimpleDynamicProxy {public static void consumer(Interface iface) {iface.doSomething();iface.somethingElse("bonobo");iface.doLastThing();}public static void main(String[] args) {RealObject real = new RealObject();//consumer(real);// 動(dòng)態(tài)代理模式的關(guān)鍵點(diǎn)1:后面兩個(gè)參數(shù)說明了如何進(jìn)行動(dòng)態(tài)代理Interface proxy = (Interface)Proxy.newProxyInstance(Interface.class.getClassLoader(),new Class[]{ Interface.class },new DynamicProxyHandler(real));consumer(proxy);}} /* Output: (95% match) doSomethingsomethingElse bonobo**** proxy: class $Proxy0, method: public abstract void Interface.doSomething(), args: nulldoSomething**** proxy: class $Proxy0, method: public abstract void Interface.somethingElse(java.lang.String), args: [Ljava.lang.Object;@42e816bonobosomethingElse bonobo*///:~空對象模式(就是把NULL用一個(gè)類去替代)中使用動(dòng)態(tài)代理去自動(dòng)創(chuàng)建空對象 ,首先看空對象模式,因?yàn)檫@個(gè)比較簡單,直接上代碼:
interface Book {// 判斷Book對象是否為空對象(Null Object)public boolean isNull();// 展示Book對象的信息內(nèi)容。public void show();}public class NullBook implements Book {public boolean isNull() {return true;}public void show() {}}public class ConcreteBook implements Book{private int ID;private String name;private String author;// 構(gòu)造函數(shù)public ConcreteBook(int ID, String name, String author) {this.ID = ID;this.name = name;this.author = author;}/***Description About show*展示圖書的相關(guān)信息*/public void show() {System.out.println(ID + "**" + name + "**" + author);}public boolean isNull(){return false;}} public class BookFactory {/***根據(jù)ConcreteBook的ID,獲取圖書對象。*@param ID 圖書的ID*@return 圖書對象*/public Book getBook(int ID) {Book book;//將原來的ConcreteBook改為Bookswitch (ID) {case 1:book = new ConcreteBook(ID, "設(shè)計(jì)模式", "GoF");break;case 2:book = new ConcreteBook(ID, "被遺忘的設(shè)計(jì)模式", "Null Object Pattern");break;default:book = new NullBook();//創(chuàng)建一個(gè)NullBook對象break;}return book;}} public static void main(String[] args) {BookFactory bookFactory = new BookFactory();Book book = bookFactory.getBook(-1);book.show();}(?)接著是利用動(dòng)態(tài)代理模式+對象模式的改版,但這個(gè)例子不能讓我明白它的好處,例子如下:
package com.typeinfo;import java.lang.reflect.InvocationHandler;import java.lang.reflect.Method;import java.lang.reflect.Proxy;interface Book {// 判斷Book對象是否為空對象(Null Object)public boolean isNull();// 展示Book對象的信息內(nèi)容。public void show();}class NullBookProxyHandler implements InvocationHandler{private Class<? extends Book> mType;private Book proxyied = new NullBook();//指定了動(dòng)態(tài)產(chǎn)生的代理實(shí)例public NullBookProxyHandler(Class<? extends Book> type){mType = type;}@Overridepublic Object invoke(Object proxy, Method method, Object[] args) throws Throwable {// TODO Auto-generated method stubSystem.out.println(mType);return method.invoke(proxyied, args);}public class NullBook implements Book {public boolean isNull() {return true;}public void show() {System.out.println("對不起,查之無物");}}}public class NullPattern {public static Book newNullBook(Class<? extends Book> type){return (Book)Proxy.newProxyInstance(NullPattern.class.getClassLoader(), new Class[]{Book.class}, new NullBookProxyHandler(type)); }public class ConcreteBook implements Book{private int ID;private String name;private String author;// 構(gòu)造函數(shù)public ConcreteBook(int ID, String name, String author) {this.ID = ID;this.name = name;this.author = author;}public void show() {System.out.println(ID + "**" + name + "**" + author);}public boolean isNull(){return false;}}public class BookFactory {public Book getBook(int ID) {Book book = newNullBook(ConcreteBook.class);//將原來的ConcreteBook改為Bookswitch (ID) {case 1:book = new ConcreteBook(ID, "設(shè)計(jì)模式", "GoF");break;case 2:book = new ConcreteBook(ID, "被遺忘的設(shè)計(jì)模式", "Null Object Pattern");break;default://book = ;break;}return book;}}public BookFactory create(){return new BookFactory();}public static void main(String[] args) {NullPattern np = new NullPattern();BookFactory bookFactory = np.create();Book book = bookFactory.getBook(-1);book.show();}}動(dòng)態(tài)代理模式整體框步驟如下:以SimpleDynamicProxy.java為例說明
//1.建立一個(gè)接口,減少耦合性interface Interface {void doSomething();void somethingElse(String arg);void doLastThing();}//2.需要代理的接口的實(shí)現(xiàn)class RealObject implements Interface {public void doSomething() { System.out.println("doSomething"); }public void somethingElse(String arg) {System.out.println("somethingElse " + arg);}public void doLastThing(){System.out.println("doLastThing");}} //3.建立一個(gè)繼承自InvocationHandler的導(dǎo)出類class DynamicProxyHandler implements InvocationHandler {private Object proxied;//3.1 你要代理的對象public DynamicProxyHandler(Object proxied) {this.proxied = proxied;}public Objectinvoke(Object proxy, Method method, Object[] args)throws Throwable {System.out.println("**** proxy: " + proxy.getClass() +", method: " + method + ", args: " + args);//可以過濾方法if(method.getName().equals("doLastThing")){return null;}if(args != null)for(Object arg : args)System.out.println(" " + arg);//6.RTTI即反射得知proxied的確切類型是RealObject,調(diào)用客戶端在第5步制定的方法return method.invoke(proxied, args);}} class SimpleDynamicProxy {public static void consumer(Interface iface) {iface.doSomething();iface.somethingElse("bonobo");iface.doLastThing();}public static void main(String[] args) {RealObject real = new RealObject();//consumer(real);// 4.具體指明你需要代理的對象,比如這里就是RealObject,因?yàn)樵谔幚砥鲀?nèi)部是Object,所以這是在編譯器無法知曉的,只能在運(yùn)行時(shí)知道具體的類型信息。Interface proxy = (Interface)Proxy.newProxyInstance(Interface.class.getClassLoader(),new Class[]{ Interface.class },new DynamicProxyHandler(real));//5.調(diào)用接口方法consumer(proxy);}}通過反射甚至可以訪問private修飾的字段,自己感覺反編譯和發(fā)射有莫大的關(guān)系。
泛型
對象和實(shí)例是一個(gè)意思,類與對象的關(guān)系就像數(shù)據(jù)類型和變量一樣。
泛型的主要目的之一就是用來指定類(如:容器)要持有什么類型的對象,代碼解釋如下:
public class Holder3<T> {private T a;//持有了T的對象,此處可以持有任何對象,可以用Object代替但是要向下轉(zhuǎn)型public Holder3(T a) { this.a = a; }public void set(T a) { this.a = a; }public T get() { return a; }public static void main(String[] args) {Holder3<Automobile> h3 =new Holder3<Automobile>(new Automobile());Automobile a = h3.get(); // No cast needed// h3.set("Not an Automobile"); // Error// h3.set(1); // Error} } ///:~在有些場景中會(huì)有一個(gè)方法返回多個(gè)對象,你可以使用創(chuàng)建類用它來持有返回的多個(gè)對象,如果再 加上泛型技術(shù)就會(huì)在編譯期確保類型安全。代碼解釋如下:
//: net/mindview/util/TwoTuple.java package net.mindview.util;public class TwoTuple<A,B> {public final A first;public final B second;public TwoTuple(A a, B b) { first = a; second = b; }public String toString() {return "(" + first + ", " + second + ")";} } ///:~如果泛型用得好,基本上不用強(qiáng)制性轉(zhuǎn)換
泛型也可以應(yīng)用于接口,比如public interface Generator<T>,在寫繼承的時(shí)候T可以寫成任意類型,比如構(gòu)造一個(gè)咖啡工廠public class CoffeeGenerator implements Generator<Coffee>,構(gòu)造一個(gè)生成Fibonacci數(shù)列的類public class Fibonacci implements Generator<Integer>,咖啡代碼如下:
//... 省略處為一些簡單類,如Latte,Mocha,Cappuccino,Americano,Breve這些類都繼承于coffee,coffee.java如下 package com.generics.coffee; public class Coffee {private static long counter = 0;private final long id = counter++;public String toString() {return getClass().getSimpleName() + " " + id;} } ///:~//: generics/coffee/CoffeeGenerator.java // Generate different types of Coffee: package com.generics.coffee; import java.util.*; import net.mindview.util.*;public class CoffeeGenerator implements Generator<Coffee> ,Iterable<Coffee> {@SuppressWarnings("rawtypes")private Class[] types = { Latte.class, Mocha.class,Cappuccino.class, Americano.class, Breve.class, };private static Random rand = new Random(47);public CoffeeGenerator() {}// For iteration:private int size = 0;public CoffeeGenerator(int sz) { size = sz; } public Coffee next() {try {return (Coffee)types[rand.nextInt(types.length)].newInstance();// Report programmer errors at run time:} catch(Exception e) {throw new RuntimeException(e);}}//解釋:內(nèi)部類實(shí)現(xiàn)迭代器,該實(shí)現(xiàn)了Iterator而CoffeeGenerator實(shí)現(xiàn)的是Iterable,要實(shí)現(xiàn)foreach循環(huán)必須實(shí)現(xiàn)這兩個(gè)接口, //從代碼看起來foreach循環(huán)是看出來了,要理解其本質(zhì)的原理需要看jvm里面的字節(jié)碼,new CoffeeGenerator(5)調(diào)用后,首先產(chǎn)生 //CoffeeIterator的實(shí)例,執(zhí)行hasNext()->next() //此處可以也可以用匿名內(nèi)部類class CoffeeIterator implements Iterator<Coffee> {int count = size;public boolean hasNext() { return count > 0; }public Coffee next() {count--;return CoffeeGenerator.this.next();}public void remove() { // Not implementedthrow new UnsupportedOperationException();}}; public Iterator<Coffee> iterator() {return new CoffeeIterator();}public static void main(String[] args) {CoffeeGenerator gen = new CoffeeGenerator();for(int i = 0; i < 5; i++)System.out.println(gen.next());for(Coffee c : new CoffeeGenerator(5))System.out.println(c);} } /* Output: Americano 0 Latte 1 Americano 2 Mocha 3 Mocha 4 Breve 5 Americano 6 Latte 7 Cappuccino 8 Cappuccino 9 *///:~Fibonacci數(shù)列的代碼如下:
package com.generics;import net.mindview.util.*;public class Fibonacci implements Generator<Integer> {private int count = 0;public Integer next() { return fib(count++); }private int fib(int n) {if(n < 2) return 1;return fib(n-2) + fib(n-1);}public static void main(String[] args) {Fibonacci gen = new Fibonacci();for(int i = 0; i < 18; i++)System.out.print(gen.next() + " ");}} /* Output:1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597 2584*///:~如果想要實(shí)現(xiàn)迭代,而且要不用內(nèi)部類的方式(CoffeeGenerator.java使用的是內(nèi)部類實(shí)現(xiàn)的迭代器模式),用適配器模式實(shí)現(xiàn),適配器模式即把兩個(gè)互不相關(guān)的接口或者類相連接,所以可以使用繼承或者組合,UML如下:
迭代如下:
package com.generics;// Adapt the Fibonacci class to make it Iterable.import java.util.*;//組合來創(chuàng)建適配器public class IterableFibonacci implements Iterable<Integer> {private Fibonacci fibonacci = new Fibonacci();private int n;public IterableFibonacci(int count) { n = count; }public Iterator<Integer> iterator() {//匿名內(nèi)部類的形式return new Iterator<Integer>() {@Overridepublic Integer next() {// TODO Auto-generated method stubn--;return fibonacci.next();//invoke next() in Fibonacci,for this extends Fibonacci}@Overridepublic boolean hasNext() {// TODO Auto-generated method stubreturn n > 0; }public void remove() { // Not implementedthrow new UnsupportedOperationException();}};} public static void main(String[] args) {for(int i : new IterableFibonacci(18))System.out.print(i + " ");}} /* Output:1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597 2584*///:~泛型應(yīng)用于方法
應(yīng)用于方法public <T> void f(T x){},其中一定要寫,不然編譯器是無法識別出參數(shù)的T
當(dāng)可變參數(shù)與方法結(jié)合:
package com.generics;//: generics/GenericVarargs.java import java.util.*;public class GenericVarargs {//此處的makeList就像是java.util.Arrays里面的asList(T... args);public static <T> List<T> makeList(T... args) {List<T> result = new ArrayList<T>();for(T item : args)result.add(item);return result;}public static void main(String[] args) {List<String> ls = makeList("A");System.out.println(ls);ls = makeList("A", "B", "C");System.out.println(ls);ls = makeList("ABCDEFFHIJKLMNOPQRSTUVWXYZ".split(""));System.out.println(ls);} } /* Output:[A][A, B, C][, A, B, C, D, E, F, F, H, I, J, K, L, M, N, O, P, Q, R, S, T, U, V, W, X, Y, Z]*///:~從上面代碼注釋可以看到makeList和asList方法很像,下面來看看asList的源碼分析
public static <T> List<T> asList(T... a) {return new ArrayList<>(a);//此處的ArrayList不是你想的java.util.ArrayList,他是Arrays里面的一個(gè)靜態(tài)內(nèi)部類}//此處是靜態(tài)內(nèi)部類的構(gòu)造器,返回一個(gè)數(shù)組,需要說明的是該內(nèi)部類并沒有實(shí)現(xiàn)add,remove等方法,因?yàn)閍sList()方法在大多數(shù)使用場景中是不用改變的,所以要構(gòu)造一個(gè)可編輯的ArrayList()用類似下面的代碼即可List<WaiterLevel> levelList = new ArrayList<WaiterLevel>(Arrays.asList("a", "b", "c")); ArrayList(E[] array) {a = Objects.requireNonNull(array);//判斷array是否為空}
利用泛型方法對前一章的生成器進(jìn)行更一步的抽象,代碼如下:
//: net/mindview/util/BasicGenerator.java // Automatically create a Generator, given a class // with a default (no-arg) constructor. package net.mindview.util; //this class can generate any Class which have default constructor by create() function,but there is a limit which is that constructor cannot pass argument(傳參) public class BasicGenerator<T> implements Generator<T> {private Class<T> type; public BasicGenerator(Class<T> type){ this.type = type; }public T next() {try {// Assumes type is a public class:return type.newInstance();} catch(Exception e) {throw new RuntimeException(e);}}// Produce a Default generator given a type token:public static <T> Generator<T> create(Class<T> type) {return new BasicGenerator<T>(type);} } ///:~更多的,我們可以對前面提到的元組進(jìn)行進(jìn)一步的抽象
//: net/mindview/util/Tuple.java // Tuple library using type argument inference. package net.mindview.util;public class Tuple {public static <A,B> TwoTuple<A,B> tuple(A a, B b) {return new TwoTuple<A,B>(a, b);}public static <A,B,C> ThreeTuple<A,B,C>tuple(A a, B b, C c) {return new ThreeTuple<A,B,C>(a, b, c);}public static <A,B,C,D> FourTuple<A,B,C,D>tuple(A a, B b, C c, D d) {return new FourTuple<A,B,C,D>(a, b, c, d);}public static <A,B,C,D,E>FiveTuple<A,B,C,D,E> tuple(A a, B b, C c, D d, E e) {return new FiveTuple<A,B,C,D,E>(a, b, c, d, e);} } ///:~java對泛型的擦除有四句話
- 泛型類型在運(yùn)行時(shí)都是Object類型
- 模板只在編譯階段有效是為了提供編譯期的類型安全,通過反射操作可以繞過編譯階段
- 在編譯期就可以知道的類型信息是可以操作的
- 所有在運(yùn)行時(shí)才能知道類型信息的操作都將無法工作
不能創(chuàng)建泛型類型數(shù)組的,一般的解決方案是在任何想要?jiǎng)?chuàng)建泛型數(shù)組的地方都是用ArrayList去創(chuàng)建。
泛型的主要目標(biāo)之一是將錯(cuò)誤檢測移入到編譯期
編譯器直接拒絕對參數(shù)列表中涉及到的通配符的方法,即add(? extends fruit)如果變成了這樣結(jié)果如下圖
?
下面代碼能夠?qū)崿F(xiàn)只能存水果的集合,且在編譯期內(nèi)就能檢查類型信息,其中第二種方式稱之為逆變。為什么逆變的方式可以實(shí)現(xiàn)?答:super關(guān)鍵字表示下界,List<? super Apple> fruit = new ArrayList<>();,而?必須要表示一個(gè)確切的類型,準(zhǔn)確來講應(yīng)該是這樣聲明一個(gè)實(shí)例即:List<? super Apple> fruit = new ArrayList<在這個(gè)括號內(nèi)部必須是Apple的父類>();即在比如List<? super Apple> fruit = new ArrayList<Fruit>(),所以當(dāng)add()的時(shí)候,可以插入Apple的子類,同樣的道理分析List<? extends Apple> flist2 = new ArrayList<這里面要插入的是Apple的子類>();所以當(dāng)add(new Apple())時(shí)候,會(huì)失敗,比如List<? extends Apple> flist2 = new ArrayList<Jonathan>();Jonathan = new Apple()//error;
//1.想要實(shí)現(xiàn)一個(gè)集合里面能裝所有類型的水果,但是在編譯期不允許裝除了水果以外的其他對象 List<Fruit> flist3 = new ArrayList<>(); flist3.addAll(Arrays.asList(new Apple())); flist3.addAll(Arrays.asList(new Orange())); System.out.println(flist3.get(1)); //2.第一種方式太復(fù)雜,下面用逆變的方式實(shí)現(xiàn) List<? super Fruit> fruit = new ArrayList<>(); fruit.add(new Apple()); fruit.add(new Orange());混型即Timestamped<Serialnumbered<Basic>> mixin其中mixin能夠調(diào)用基類的所有函數(shù),在C++中,這是顯然的,但是在java中可以這樣聲明,但不能調(diào)用基類的任何函數(shù)只能調(diào)用Timestamped類中的函數(shù),所以必須使用有些設(shè)計(jì)模式來代替,其中涉及到裝飾器模式,和用動(dòng)態(tài)代理(即我們可以動(dòng)態(tài)注入類方法)來實(shí)現(xiàn)混合,但是結(jié)果都沒有C++中方便直接。
implements和extends關(guān)鍵字實(shí)現(xiàn):
package com.generics; //: generics/Mixins.java import java.util.*;interface TimeStamped { long getStamp(); }class TimeStampedImp implements TimeStamped {private final long timeStamp;public TimeStampedImp() {timeStamp = new Date().getTime();}public long getStamp() { return timeStamp; } }interface SerialNumbered { long getSerialNumber(); }class SerialNumberedImp implements SerialNumbered {private static long counter = 1;private final long serialNumber = counter++;public long getSerialNumber() { return serialNumber; } }interface Basic {public void set(String val);public String get(); }class BasicImp implements Basic {private String value;public void set(String val) { value = val; }public String get() { return value; } } // for Mixin2.java,Timestamped<Serialnumbered<Basic>> mixin = new Timestamped();,mixin can not invoke set() function of Basic,but c++ is capable to do it. //so in java, use implements and extends keywords to realize it. class Mixin extends BasicImp implements TimeStamped, SerialNumbered {//if use this,you must have a instance of response to interfaceprivate TimeStamped timeStamp = new TimeStampedImp();private SerialNumbered serialNumber =new SerialNumberedImp();public long getStamp() { return timeStamp.getStamp(); }public long getSerialNumber() {return serialNumber.getSerialNumber();} }public class Mixins {public static void main(String[] args) {Mixin mixin1 = new Mixin(), mixin2 = new Mixin();mixin1.set("test string 1");mixin2.set("test string 2");System.out.println(mixin1.get() + " " +mixin1.getStamp() + " " + mixin1.getSerialNumber());System.out.println(mixin2.get() + " " +mixin2.getStamp() + " " + mixin2.getSerialNumber());} } /* Output: (Sample) test string 1 1132437151359 1 test string 2 1132437151359 2 *///:~裝飾器模式實(shí)現(xiàn)(并沒有完全實(shí)現(xiàn)):
package com.generics.decorator;//: generics/decorator/Decoration.javaimport java.util.*;class Basic {private String value;public void set(String val) { value = val; }public String get() { return value; } }class Decorator extends Basic {protected Basic basic;public Decorator(Basic basic) { this.basic = basic; }public void set(String val) { basic.set(val); }public String get() { return basic.get(); } } class TimeStamped extends Decorator {private final long timeStamp;public TimeStamped(Basic basic) {super(basic);timeStamp = new Date().getTime();}public long getStamp() { return timeStamp; } }class SerialNumbered extends Decorator {private static long counter = 1;private final long serialNumber = counter++;public SerialNumbered(Basic basic) { super(basic); }public long getSerialNumber() { return serialNumber; } } //this is decoration design patternspublic class Decoration {public static void main(String[] args) {TimeStamped t = new TimeStamped(new Basic());// because timestamped extends Basict.set("fasdfa");//realize such as TimeStamped<SerialNumbered<Basic>> mixin1, mixin2TimeStamped t2 = new TimeStamped(new SerialNumbered(new Basic()));//! t2.getSerialNumber(); // Not available, obviouslySerialNumbered s = new SerialNumbered(new Basic());SerialNumbered s2 = new SerialNumbered(new TimeStamped(new Basic()));//! s2.getStamp(); // Not available} } ///:~動(dòng)態(tài)代理模式實(shí)現(xiàn):
package com.generics;//: generics/DynamicProxyMixin.java import java.lang.reflect.*; import java.util.*; import net.mindview.util.*; import static net.mindview.util.Tuple.*;class MixinProxy implements InvocationHandler {Map<String,Object> delegatesByMethod;public MixinProxy(TwoTuple<Object,Class<?>>... pairs) {delegatesByMethod = new HashMap<String,Object>();for(TwoTuple<Object,Class<?>> pair : pairs) {for(Method method : pair.second.getMethods()) {String methodName = method.getName();System.out.println(methodName + "()");// The first interface in the map// implements the method.if (!delegatesByMethod.containsKey(methodName))delegatesByMethod.put(methodName, pair.first);// this is the most important, because this inject all functions of pairs}}} public Object invoke(Object proxy, Method method,Object[] args) throws Throwable {System.out.println("invoke() is invoked"); String methodName = method.getName();Object delegate = delegatesByMethod.get(methodName);return method.invoke(delegate, args);}@SuppressWarnings("unchecked")public static Object newInstance(TwoTuple... pairs) {Class[] interfaces = new Class[pairs.length];for(int i = 0; i < pairs.length; i++) {interfaces[i] = (Class)pairs[i].second;//second represent XXX.class}ClassLoader cl =pairs[0].first.getClass().getClassLoader();return Proxy.newProxyInstance(cl, interfaces, new MixinProxy(pairs));} } public class DynamicProxyMixin {public static void main(String[] args) {Object mixin = MixinProxy.newInstance(tuple(new BasicImp(), Basic.class),tuple(new TimeStampedImp(), TimeStamped.class),tuple(new SerialNumberedImp(),SerialNumbered.class));//Basic b = (Basic)mixin;TimeStamped t = (TimeStamped)mixin;SerialNumbered s = (SerialNumbered)mixin;b.set("Hello");System.out.println(b.get());System.out.println(t.getStamp());System.out.println(s.getSerialNumber());} } /* get() set() getStamp() getSerialNumber() invoke() is invoked invoke() is invoked Hello invoke() is invoked 1489219456567 invoke() is invoked 1 *///:~靜態(tài)類型檢查即在程序沒有運(yùn)行時(shí)就能夠通過檢查源代碼確定類型安全,與動(dòng)態(tài)類型相對應(yīng)
潛在類型機(jī)制即直接可以用模板T,而不用指定該模板屬于哪個(gè)基類,比如在C++里面就可以直接定義
template<class T> void perform(T anything) {anything.speak();anything.sit(); }而在java中必須要指明邊界
class Communicate { //must specify the bounds of generic type,but C++ is not necessary public static <T extends Performs> void perform(T performer) { performer.speak(); performer.sit(); } }java對潛在類型機(jī)制的補(bǔ)償?shù)囊环N方式是反射,如下
class CommunicateReflectively { //接受一個(gè)Object,然后看是哪個(gè)類 public static void perform(Object speaker) { Class<?> spkr = speaker.getClass(); try { try { Method speak = spkr.getMethod("speak"); speak.invoke(speaker); } catch(NoSuchMethodException e) { print(speaker + " cannot speak"); } try { Method sit = spkr.getMethod("sit"); sit.invoke(speaker); } catch(NoSuchMethodException e) { print(speaker + " cannot sit"); } } catch(Exception e) { throw new RuntimeException(speaker.toString(), e); } } }15.17中15.17.2與15.17.3,15.17.4沒理解
應(yīng)用于序列的泛型技術(shù)很多都會(huì)涉及到Iterable接口
數(shù)組
在java中數(shù)組是一種效率最高的存儲(chǔ)和隨機(jī)訪問對象應(yīng)用序列的方式
Comparable接口和Comaprator接口用于排序,jdk中運(yùn)用策略設(shè)計(jì)模式將“保持不變的事物與會(huì)發(fā)生改變的事物相分離”,代碼如下:
//Comparable class Student implements Comparable<Student>{private String name;private int age;private float score;public Student(String name, int age, float score) {this.name = name;this.age = age;this.score = score;}public String toString(){return name+"\t\t"+age+"\t\t"+score;}@Overridepublic int compareTo(Student o) {// TODO Auto-generated method stubif(this.score>o.score)//score是private的,為什么能夠直接調(diào)用,這是因?yàn)樵赟tudent類內(nèi)部return -1;//由高到底排序else if(this.score<o.score)return 1;else{if(this.age>o.age)return 1;//由底到高排序else if(this.age<o.age)return -1;elsereturn 0;}} }public class ComparableDemo01 {public static void main(String[] args) {// TODO Auto-generated method stubStudent stu[]={new Student("zhangsan",20,90.0f),new Student("lisi",22,90.0f),new Student("wangwu",20,99.0f),new Student("sunliu",22,100.0f)};java.util.Arrays.sort(stu);for(Student s:stu){System.out.println(s);}} }//Comparator package edu.sjtu.ist.comutil;import java.util.Comparator;class Student {private String name;private int age;private float score;public Student(String name, int age, float score) {this.name = name;this.age = age;this.score = score;}public String getName() {return name;}public void setName(String name) {this.name = name;}public int getAge() {return age;}public void setAge(int age) {this.age = age;}public float getScore() {return score;}public void setScore(float score) {this.score = score;}public String toString(){return name+"\t\t"+age+"\t\t"+score;}}class StudentComparator implements Comparator<Student>{@Overridepublic int compare(Student o1, Student o2) {// TODO Auto-generated method stubif(o1.getScore()>o2.getScore())return -1;else if(o1.getScore()<o2.getScore())return 1;else{if(o1.getAge()>o2.getAge())return 1;else if(o1.getAge()<o2.getAge())return -1;else return 0;}}} public class ComparableDemo02 {public static void main(String[] args) {// TODO Auto-generated method stubStudent stu[]={new Student("zhangsan",20,90.0f),new Student("lisi",22,90.0f),new Student("wangwu",20,99.0f),new Student("sunliu",22,100.0f)};java.util.Arrays.sort(stu,new StudentComparator());for(Student s:stu){System.out.println(s);}}}當(dāng)你使用最近的java版本編程時(shí),應(yīng)該優(yōu)先選擇容器而不是數(shù)組,只有在證明性能成為問題時(shí),你才應(yīng)該講程序重構(gòu)為使用數(shù)組
容器源碼解讀
繼承結(jié)構(gòu)代碼如下:
public interface Iterable<T>{...}public interface Collection<E> extends Iterable<E>{...} public interface Set<E> extends Collection<E>{...} public interface SortedSet<E> extends Set<E>{ Comparator<? super E> comparator();} public interface List<E> extends Collection<E>{...}- 抽象類實(shí)現(xiàn)接口,可以不用實(shí)現(xiàn)其全部的方法即可以篩選一些方法來實(shí)現(xiàn),比如:
java
//in this abstract class, the equals() funtion is not implemented
public abstract class AbstractCollection<E> implements Collection<E> {...}
//next eg:
interface test{
void m();
void f();
}
abstract class test2 implements test{
@Override
public void m() {
// TODO Auto-generated method stub
}
}
?
總結(jié)
以上是生活随笔為你收集整理的java编程思想读书笔记的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Spring Boot处理JSON数据
- 下一篇: ug初始化错误未能创建服务器,UG10.