Translation Tipatterns - Flexible Structure (Flexible Structure)

xiaoxiao2021-03-06  99

Flexible Structure

Combining Composite Composite composite models, it is important to all, these elements that belong to some-Whole are can be operated, that is, the operation of a node / combination (Composite) Also acts on all child nodes of the node. GOF gives the implementation details of how to include and visited sub-nodes in the base class interface, but it seems to have no need. The example given below, the Composite class is just a simple inheritance of the ArrayList class to implement the functionality of the (child node).

//: composite: CompositeStructure.javapackage composite; import java.util *; import junit.framework *; interface Component {void operation ();} class Leaf implements Component {private String name; public Leaf (String name) {this.. .name = name;} public String toString () {return name;} public void operation () {System.out.println (this);}} class Node extends ArrayList implements Component {private String name; public Node (String name) {this.name = name;} public string toString () {return name;} public void Operation (); for (Iterator IT = Iterator (); it.hasnext ();); ()). Operation ();}} public class compositestructure extension testcase {public void test () {node root = new node ("root"); root.add (New Leaf1) ); Node C2 = new node ("node1"); c2.add (New Leaf ("leaf2")); c2.add (New Leaf3)); root.add (c2); c2 = new node ("Node2"); C2.Add (New Leaf ("Leaf4")); C2.Add (New Leaf ("Leaf5")); root.add (c2); root.operation ();} public static void main (String args []) {junit.textui.t ESTRunner.Run (Compositestructure.class);}} ///: ~

The above method may be "the easiest way to implement the Composite mode", of course, this method may have problems when used for large systems. However, the best approach may start from the easiest way, but only change it when you need it.

table of Contents

转载请注明原文地址:https://www.9cbs.com/read-124410.html

New Post(0)