初识埃克尔--【初读:Java编程思想】

“上帝赋予人类说话的能力,而言语又创造了思想,思想是人类对宇宙的度量。”      --《Prometheus Unbound》,Shelley

此篇长文我会更新对 埃克尔《Java编程思想第四版》的思想感悟以及内容实践,包括对其中经典思想的碰撞,对作者提问问题的寻根和问题延展,对编程思想的感悟,以不一定连载的方式更新此文,感谢计算机大师的著作!

 

复用类

【小记】规范的复用类为项目重构提供保障

合理的private对象成员保证了类开发者对底层实现的权力,也就为后期项目重构提供了基础的底层逻辑实现的保障

【思考与存疑】

架构设计初期对基类的实现考量,是否是架构稳定后其拥有可扩展性和灵活性的关键呢?

多态

【理解】用大脑过一边如下程序的对象运行过程,如果没有运算正确,那么用编辑器一步步进行堆栈对象分析,有助于你理解面向对象

代码:

//practice
class Shared {
	private int refcount=0;
	private static long counter=0;
	private final long id = counter++;
	public Shared() {
		System.out.println("Creating"+this);
	}
	public void addRef() {
		refcount++;
	}
	protected void dispose() {
		if(--refcount==0) {
			System.out.println("Disposing"+this);
		}
	}
	public String toString() {
		return "Shared"+id;
	}
}

class Composing {
	private Shared shared;
	private static long counter=0;
	private final long id = counter++;
	public Composing(Shared shared) {
		System.out.println("Creating"+this);
		this.shared= shared;
		this.shared.addRef();
		
	}
	protected void dispose() {
		System.out.println("Disposing"+this);
		shared.dispose();
	}
	
	public String toString() {
		return "Composing"+id;
	}
}

public class java1 {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		//Chinchilla rat1 = new Chinchilla("37s");
		
		//practise
		Shared shared =new Shared();
		Composing[] composing = {new Composing(shared),new Composing(shared),new Composing(shared),new Composing(shared),new Composing(shared)};
		for(Composing c:composing) {
			c.dispose();
		}
	}

}

  正确的运行结果:

CreatingShared0
CreatingComposing0
CreatingComposing1
CreatingComposing2
CreatingComposing3
CreatingComposing4
DisposingComposing0
DisposingComposing1
DisposingComposing2
DisposingComposing3
DisposingComposing4
DisposingShared0

 


 

内部类

 

posted @ 2018-12-09 10:52  devmaxing  阅读(152)  评论(0)    收藏  举报