//未用模式
/*class Leaf{
private String name;
public Leaf(String name) {
super();
this.name = name;
}
public void printStruct(int d)
for(int i=0;i<d;i++) {
System.out.print(" ");
System.out.println("-"+name);
}
}
class Composite{
private Collection<Composite> childComposite = new ArrayList<Composite>();
private Collection<Leaf> childLeaf = new ArrayList<Leaf>();
private String name;
public Composite(String name) {
super();
this.name = name;
}
public void AddComposite(Composite c) {
this.childComposite.add(c);
}
public void AddLeaf(Leaf leaf) {
this.childLeaf.add(leaf);
}
public void printStruct(int d) {
for(int i=0;i<d;i++)
System.out.print(" ");
System.out.println("+"+name);
for(Leaf leaf : childLeaf) {
leaf.printStruct(d+2);
}
for(Composite c : childComposite) {
c.printStruct(d+2);
}
}
}
public class Main {
public static void main(String args[])
{
Composite root = new Composite("服装");
Composite c1 = new Composite("男装");
Composite c2 = new Composite("女装");
Leaf l1 = new Leaf("衬衣");
Leaf l2 = new Leaf("夹克");
Leaf l3 = new Leaf("裙子");
Leaf l4 = new Leaf("套装");
root.AddComposite(c1);
root.AddComposite(c2);
c1.AddLeaf(l1);
c1.AddLeaf(l2);
c2.AddLeaf(l3);
c2.AddLeaf(l4);
root.printStruct(0);
}
}*/
//组合模式
abstract class Component{
protected String name;
public Component(String name) {
super();
this.name = name;
}
public abstract void Add(Component c);
public abstract void Remove(Component c);
public abstract void Display(int depth);
}
class Leaf extends Component{
public Leaf(String name) {
super(name);
}
public void Add(Component c) {
// TODO Auto-generated method stub
System.out.println("Cannot add a leaf");
}
public void Remove(Component c) {
// TODO Auto-generated method stub
System.out.println("Cannot remove from a leaf");
}
public void Display(int depth) {
// TODO Auto-generated method stub
for(int i=0;i<depth;i++)
System.out.print(" ");
System.out.println("-"+name);
}
}
class Composite extends Component{
private ArrayList<Component> component = new ArrayList<Component>();
public Composite(String name) {
super(name);
}
public void Add(Component c) {
// TODO Auto-generated method stub
component.add(c);
}
public void Remove(Component c) {
// TODO Auto-generated method stub
component.remove(c);
}
public void Display(int depth) {
// TODO Auto-generated method stub
for(int i=0;i<depth;i++)
System.out.print(" ");
System.out.println("+"+name);
for(Component c : component) {
c.Display(depth + 2);
}
}
}
public class Main {
public static void main(String args[])
{
Composite root = new Composite("服装");
Composite c1 = new Composite("男装");
Composite c2 = new Composite("女装");
Leaf l1 = new Leaf("衬衣");
Leaf l2 = new Leaf("夹克");
Leaf l3 = new Leaf("裙子");
Leaf l4 = new Leaf("套装");
root.Add(c1); root.Add(c2);
c1.Add(l1); c1.Add(l2);
c2.Add(l3); c2.Add(l4);
root.Display(0);
}
}
组合模式一步步实现
最新推荐文章于 2024-07-13 18:35:09 发布