GMF中,删除节点和连线的另一种实现

问题

在GMF中,如果需要programmatically删除节点或连线,在google中我们很容易搜索到《GMF中,删除节点和连线的实现》一文(我并不确定这是原创作者的原始链接),很多人可能都使用这种实现。这是一种很好的实现,但有时候也有其缺点--除了需要删除View和Edge外,还需要删除model,在element对应于各种不同的model时,显然需要写大量if else来处理不同的model。

实现

我们可以有另一种实现,通过request和command来实现,以下代码删除某个节点上所有的连线

	public void deleteConnections(ShapeNodeEditPart editpart)
	{
		CompoundCommand compoundCommand =new CompoundCommand("delete all connections");
		List connections = editpart.getTargetConnections();
		connections.addAll(editpart.getSourceConnections());
		GroupRequest deleteReq = new GroupRequest(RequestConstants.REQ_DELETE);
		deleteReq.setEditParts(connections);
		for (int i = 0; i < connections.size(); i++) {
			EditPart object = (EditPart) connections.get(i);
			Command deleteCmd = object.getCommand(deleteReq);
			if (deleteCmd != null)
				compoundCommand.add(deleteCmd);
		}
		
		editpart.getDiagramEditDomain().getDiagramCommandStack().execute(compoundCommand);
	}

删除多个节点

public void deleteNodes(List editparts)
	{
		CompoundCommand compoundCommand =new CompoundCommand("delete nodes");
		GroupRequest deleteReq = new GroupRequest(RequestConstants.REQ_DELETE);
		
		deleteReq.setEditParts(editparts);
		for (int i = 0; i < editparts.size(); i++) {
			EditPart object = (EditPart) editparts.get(i);
			Command deleteCmd = object.getCommand(deleteReq);
			if (deleteCmd != null)
				compoundCommand.add(deleteCmd);
		}
		
		((ShapeNodeEditPart)editparts.get(0)).getDiagramEditDomain().getDiagramCommandStack().execute(compoundCommand);
	}

这种方式的好处是,不必关心底层model的删除,因为每个element对应的command中,GMF已经帮我们实现了,更加简单,且符合开放-闭合原则。并且,undo和redo也已经实现。

 

参考

org.eclipse.gef.ui.actions.DeleteAction

 

Binhua Liu原创,写于2013/8/25。

原文地址:https://www.cnblogs.com/Binhua-Liu/p/3280596.html