Я на самом деле читаю книгу о шаблонах проектирования в 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
}