一个父子关系的接口设计
有两个接口: Parent, Child. Parent生产Child后会在内部保持Child的引用, 现在的需求是如何有效在Child中实现Close()方法.
interface Parent{
Child getChild(int id);
}
interface Child{
// 如何有效地实现这个接口?
void Close();
}
class StandardParent{
Map children;
public Child getChild(int id){
Child c = new StandardChild();
c.setId(id);
children.add(id, c);
return c;
}
}
class StandardChild{
// 如何有效地实现这个接口, 以删除Child在Parent中的引用?
public void Close(){
}
}
------解决方案--------------------StandardParent里面提供一个getChildren()方法,返回那个MAP,然后用ID就可以取到这个Child,删掉就可以了
------解决方案--------------------class StandardChild{
private Parent parent;
public StandardChild(Parent parent){
this.parent = parent;
}
pubic void close(){
parent.delete(this.getId());
}
}
------解决方案--------------------你可以通过observer来实现阿,(mediator也可以)
class StandardParent implements Observer{
public void update(Observable o, Object arg){
//从Map中删除disposed标识为true的child
}
}
class StandardChild implements Observable{
boolean disposed = false;
pubic void close(){
this.disposed = true;
setChanged();
notifyObservers();
}
public boolean isDisposed(){
return disposed;
}
}
------解决方案--------------------可以考虑用回调,也就是用listener
for example
class StandardChild{
private List listeners;
public StandardChild(){
}
public void addCloseListener(ClostListener l){
synchronized (listeners) {
listeners.add(l);
}
}
pubic void close(){
//do your task here
// call back
synchronized (listeners) {
for (CloseListener l : listeners) {
l.onClose(new CloseEvent(this.getId()));
}
}
}
}
interface CloseListener {
void onClose(CloseEvent e);
}
class CloseEvent {
int id;
....
}
class StandardParent{
----Map children;
----public Child getChild(int id){
--------Child c = new Child();
--------c.setId(id);
--------children.add(id, c);
c.addCloseListener(new CloseListener() {
public void onClose(CloseEvent e) {
//do something here
children.delete(e.getId());
}
});
--------return c;
----}
}
仅供参考