我其實讀一本書在Java設計模式,我是一個新手:)投到一個抽象類......這怎麼可能?
http://www.amazon.com/Design-Patterns-Java-TM-Software/dp/0321333020/約組成圖案的章節我碰到那個讓我爲難,強制轉換爲一個抽象類代碼,我也有不太清楚當子類調用抽象超類的構造函數時會發生什麼,請你幫助我!
,我說的是在isTree(設置訪問)
MachineComponent c = (MachineComponent) i.next();
if (visited.contains(c) || !c.isTree(visited))
我們如何可以調用子類的isTree
方法的石膏,之後他的抽象超 而isTree
超類方法是投抽象?
這裏有兩類片段:
package com.oozinoz.machine;
/*
* Copyright (c) 2001, 2005. Steven J. Metsker.
*/
import java.util.*;
import com.oozinoz.iterator.ComponentIterator;
/**
* Objects of this class represent either individual machines or composites of
* machines.
*/
public abstract class MachineComponent {
/*
* Subclasses implement this to support the isTree() algorithm.
*/
protected abstract boolean isTree(Set s);
// rest of class omitted
}
2:
package com.oozinoz.machine;
/*
* Copyright (c) 2001, 2005. Steven J. Metsker.
*/
import java.util.*;
import com.oozinoz.iterator.ComponentIterator;
import com.oozinoz.iterator.CompositeIterator;
/**
* Represent a collection of machines: a manufacturing line, a bay, or a
* factory.
*/
public class MachineComposite extends MachineComponent {
protected List components = new ArrayList();
/**
* @param visited a set of visited nodes
* @return true if this composite is a tree
* @see MachineComponent#isTree()
*/
protected boolean isTree(Set visited) {
visited.add(this);
Iterator i = components.iterator();
while (i.hasNext()) {
MachineComponent c = (MachineComponent) i.next();
if (visited.contains(c) || !c.isTree(visited))
return false;
}
return true;
}
// rest of class omitted
}
請正確格式化你的代碼,如果你打算只轉儲在整個文件 – 2012-01-02 00:26:14