0

XML ドキュメントのさまざまな要素にさまざまな属性を追加する必要があります。新しい属性を追加するためのロジックは非常に独立しています。これらの属性を追加するための一連のクラスを作成します。どのデザイン パターンを使用するべきか迷っています。次のオプションを考えました。

  1. デコレーター サブクラスが多すぎます。XML を装飾するために 10 から 20 個のモジュールがあるかもしれませんが、20 個のサブクラスは好きではありません。

  2. 責任の連鎖: 個々のモジュールは独立しているため、プロセス全体を完了する必要はありません。

どんな提案でも大歓迎です。

ありがとう。

4

1 に答える 1

1

あなたは実際に続けるためにそれほど多くの文脈を与えていません。プログラミング言語、使用しているXML解析モデル、および特定の要素に属性が必要かどうかを判断するために必要なコンテキストの量。

したがって、次の1つのアプローチがあります。

  • Javaを想定
  • DOMアプローチに少し似た抽象的な概念的なオブジェクトのセット(ElementおよびXMLDocument)を使用します-XMLツリー内のノードに対する実際のインターフェイスを置き換えます
  • 要素マッチングロジックは自己完結型であると想定しています。つまり、ロジックは、要素自体の名前またはその他の属性に基づいて特定の属性を適用する必要があるかどうかを判断でき、親、子、または祖先について知る必要はありません。

ちなみに、このコードはコンパイルおよびテストされていません。これは、アプローチの単なる例示です。

public interface ElementManipulator {
    public void manipulateElement(Element elem);
}

public class AManipulator implements ElementManipulator {
    public void manipulateElement(Element elem) {
        if (elem.name == "something-A-cares-about") {
            //add A's attribute(s) to elem
        }
    }
}

public class BManipulator implements ElementManipulator {
    public void manipulateElement(Element elem) {
        if (elem.name == "something-B-cares-about") {
            //add B's attribute(s) to elem
        }
    }
}

public class XMLManipulator {
    ArrayList<? extends ElementManipulator> manipulators;

    public XMLManipulator () {
        this.manipulators = new ArrayList<? extends ElementManipulator>();
        this.manipulators.add(new AManipulator());
        this.manipulators.add(new BManipulator());
    }

    public void manipulateXMLDocument(XMLDocument doc) {
        Element rootElement = doc.getRootElement();
        this.manipulateXMLElement(rootElement);
    }        

    /**
     * Give the provided element, and all of it's children, recursively, 
     * to all of the manipulators on the list.
     */
    public void manipulateXMLElement(Element elem) {
        foreach (ElementManipulator manipulator : manipulators) {
            manipulator.manipulateElement(elem);
        }            
        ArrayList<Element> children = elem.getChildren();
        foreach(Element child: children) {
            this.manipulateXMLElement(child);  
        }
    }
} 
于 2012-05-03T22:26:48.383 に答える