1、 实例概况
用组合模式对购物网站的商品进管理,绘制选择模式的结构图,并绘制该案例的类图,并编写代码演示结果,运行结果样例显示如右图所示。
2、所用模式结构视图
3、实例类图
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 list=new ArrayList();
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
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
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、结果
Original: https://www.cnblogs.com/chaos2022/p/16171243.html
Author: cxc超小超
Title: 组合模式之对购物网站
原创文章受到原创版权保护。转载请注明出处:https://www.johngo689.com/608886/
转载文章受原作者版权保护。转载请注明原作者出处!