良いアルゴリズム

3325 ワード


Map-の代わりに配列を使用--プロセスを埋め込む
 
public void installEditPolicy(Object key, EditPolicy editPolicy) {
	Assert.isNotNull(key, "Edit Policies must be installed with keys");//$NON-NLS-1$
	if (policies == null) {
		policies = new Object[2];
		policies[0] = key;
		policies[1] = editPolicy;
	} else {
		int index = 0;
		while (index < policies.length && !key.equals(policies[index]))
			index += 2;
		if (index < policies.length) {
			index++;
			EditPolicy old = (EditPolicy)policies[index];
			if (old != null && isActive())
				old.deactivate();
			policies[index] = editPolicy;
		} else {
			Object newPolicies[] = new Object[policies.length + 2];
			System.arraycopy(policies, 0, newPolicies, 0, policies.length);
			policies = newPolicies;
			policies[index] = key;
			policies[index + 1] = editPolicy;
		}
	}
	
	if (editPolicy != null) {
		editPolicy.setHost(this);
		if (isActive())
			editPolicy.activate();
	}
}

 
 
 
Mapの代わりに配列を使用--取得プロセス
 
public EditPolicy getEditPolicy(Object key) {
	if (policies != null)
		for (int i = 0; i < policies.length; i += 2) {
			if (key.equals(policies[i]))
				return (EditPolicy) policies[i + 1];
		}
	return null;
}
 
 
ModelとEditPartは1つ1つの対応関係があり、同期機能
protected void refreshChildren() {
	int i;
	EditPart editPart;
	Object model;

	Map modelToEditPart = new HashMap();
	List children = getChildren();

	for (i = 0; i < children.size(); i++) {
		editPart = (EditPart)children.get(i);
		modelToEditPart.put(editPart.getModel(), editPart);
	}

	List modelObjects = getModelChildren();

	for (i = 0; i < modelObjects.size(); i++) {
		model = modelObjects.get(i);

		//Do a quick check to see if editPart[i] == model[i]
		if (i < children.size()
			&& ((EditPart) children.get(i)).getModel() == model)
				continue;

		//Look to see if the EditPart is already around but in the wrong location
		editPart = (EditPart)modelToEditPart.get(model);

		if (editPart != null)
			reorderChild (editPart, i);
		else {
			//An editpart for this model doesn't exist yet.  Create and insert one.
			editPart = createChild(model);
			addChild(editPart, i);
		}
	}
	List trash = new ArrayList();
	for (; i < children.size(); i++)
		trash.add(children.get(i));
	for (i = 0; i < trash.size(); i++) {
		EditPart ep = (EditPart)trash.get(i);
		removeChild(ep);
	}
}
 
インタフェースEditPartが存在し、addNotifyメソッドを定義
マルチステートを使用して再帰呼び出しを実現---EditPart実装クラスはaddNotifyメソッドを実装する際にchildrenを再帰的に遍歴し、addNotify動作も行う必要がある.
public void addNotify() {
	register();
	createEditPolicies();
	List children = getChildren();
	for (int i = 0; i < children.size(); i++)
		((EditPart)children.get(i))
			.addNotify();
	refresh();
}