组合模式之对购物网站

1、 实例概况

用组合模式对购物网站的商品进管理,绘制选择模式的结构图,并绘制该案例的类图,并编写代码演示结果,运行结果样例显示如右图所示。

12

 

2、所用模式结构视图

3

3、实例类图

4

4、实例实现代码

4.1抽象构件类ZC32Clothing

public abstract class ZC32Clothing {
	protected String name;
	public ZC32Clothing(String name) {
		this.name=name;
	}
	public abstract void add(ZC32Clothing c);
	public abstract void remove(ZC32Clothing c);
	public abstract void display(int depth);	
}

4.2容器构建类ZC32SexClothing(男女服装类)

import java.util.ArrayList;
import java.util.List;

public class ZC32SexCloting extends ZC32Clothing {
	private List<ZC32Clothing> list=new ArrayList<ZC32Clothing>();
	public ZC32SexCloting(String name) {
		super(name);
		 
	}

	public void add(ZC32Clothing c) {
			list.add(c);
	}
	public void remove(ZC32Clothing c) {
		list.remove(c);
 
	}
	public void display(int depth) {
		for(int i=1;i<=depth;++i)System.out.print("-");
		System.out.println(name);
		for(ZC32Clothing c:list)c.display(depth+4);
	}
}

4.3叶子构建类ZC32Type(具体服装类)

public class ZC32Type extends ZC32Clothing{
	 
		public ZC32Type(String name) {
			super(name);
	 
		}
		public void add(ZC32Clothing c) {
			System.out.println("不能添加");
			
		}
		public void remove(ZC32Clothing c) {
			System.out.println("不能删除");
			
		}
		public void display(int depth) {
			for(int i=1;i<=depth;++i)System.out.print("-");
			System.out.println(name);
		}
	}

4.4客户端测试类ZC32Client

public class ZC32Client {
	public static void main(String[] args) {
		ZC32Clothing c=new ZC32SexCloting("服装");
		
		ZC32Clothing man=new ZC32SexCloting("男装");
		ZC32Clothing woman=new ZC32SexCloting("女装");
		
		ZC32Clothing man1=new ZC32Type("衬衣");
		ZC32Clothing man2=new ZC32Type("夹克");
		ZC32Clothing woman1=new ZC32Type("裙子");
		ZC32Clothing woman2=new ZC32Type("套装");
				
		c.add(man);
		c.add(woman);
		
		man.add(man1);
		man.add(man2);
		
		woman.add(woman1);
		woman.add(woman2);
		
		c.display(1);
 
	}

}

5、结果

5

posted @ 2022-04-20 18:53  cxc超小超  阅读(42)  评论(0)    收藏  举报