标签:ring att remove 透明 alt 文本文件 模式 publish mat
典型的抽象构件角色代码:
1 public abstract class Component 2 { 3 public abstract void add(Component c); 4 public abstract void remove(Component c); 5 public abstract Component getChild(int i); 6 public abstract void operation(); 7 }
典型的叶子构件角色代码:
1 public class Leaf extends Component 2 { 3 public void add(Component c) 4 { //异常处理或错误提示 } 5 6 public void remove(Component c) 7 { //异常处理或错误提示 } 8 9 public Component getChild(int i) 10 { //异常处理或错误提示 } 11 12 public void operation() 13 { 14 //实现代码 15 } 16 }
典型的容器构件角色代码:
1 public class Composite extends Component 2 { 3 private ArrayList list = new ArrayList(); 4 5 public void add(Component c) 6 { 7 list.add(c); 8 } 9 10 public void remove(Component c) 11 { 12 list.remove(c); 13 } 14 15 public Component getChild(int i) 16 { 17 (Component)list.get(i); 18 } 19 20 public void operation() 21 { 22 for(Object obj:list) 23 { 24 ((Component)obj).operation(); 25 } 26 } 27 }
实例代码(JAVA):
1 //抽象构建 2 public abstract class MyElement 3 { 4 public abstract void eat(); 5 } 6 7 //容器构建 8 import java.util.*; 9 10 public class Plate extends MyElement 11 { 12 private ArrayList list=new ArrayList(); 13 14 public void add(MyElement element) 15 { 16 list.add(element); 17 } 18 19 public void delete(MyElement element) 20 { 21 list.remove(element); 22 } 23 24 public void eat() 25 { 26 for(Object object:list) 27 { 28 ((MyElement)object).eat(); //递归 29 } 30 } 31 } 32 33 //叶子构建 34 public class Apple extends MyElement 35 { 36 public void eat() 37 { 38 System.out.println("吃苹果!"); 39 } 40 } 41 42 //叶子构建 43 public class Banana extends MyElement 44 { 45 public void eat() 46 { 47 System.out.println("吃香蕉!"); 48 } 49 } 50 51 //叶子构建 52 public class Pear extends MyElement 53 { 54 public void eat() 55 { 56 System.out.println("吃梨子!"); 57 } 58 } 59 60 //客户端 61 public class Client 62 { 63 public static void main(String a[]) 64 { 65 MyElement obj1,obj2,obj3,obj4,obj5; 66 Plate plate1,plate2,plate3; 67 68 obj1=new Apple(); 69 obj2=new Pear(); 70 plate1=new Plate(); 71 plate1.add(obj1); 72 plate1.add(obj2); 73 74 obj3=new Banana(); 75 obj4=new Banana(); 76 plate2=new Plate(); 77 plate2.add(obj3); 78 plate2.add(obj4); 79 80 obj5=new Apple(); 81 plate3=new Plate(); 82 plate3.add(plate1); 83 plate3.add(plate2); 84 plate3.add(obj5); 85 86 plate3.eat(); 87 } 88 }
运行结果:
1 <?xml version="1.0"?> 2 <books> 3 <book> 4 <author>Carson</author> 5 <price format="dollar">31.95</price> 6 <pubdate>05/01/2001</pubdate> 7 </book> 8 <pubinfo> 9 <publisher>MSPress</publisher> 10 <state>WA</state> 11 </pubinfo> 12 </books>
透明组合模式
安全组合模式
标签:ring att remove 透明 alt 文本文件 模式 publish mat
原文地址:https://www.cnblogs.com/WindSun/p/10263376.html