java语言使用组合模式描述商场的服装店,专卖店,衣服,裤子的关系,设计代码
时间: 2023-06-03 13:01:47 浏览: 87
好的,这个问题属于编程问题,我会尽力回答。以下是Java代码实现组合模式来描述商场的服装店、专卖店、衣服和裤子之间的关系:
首先,我们需要定义一个抽象类 Component,它代表着组合中的对象,可以是单个对象或者是一组对象的集合,定义如下:
```
public abstract class Component {
protected String name;
public Component(String name) {
this.name = name;
}
public abstract void add(Component component);
public abstract void remove(Component component);
public abstract void display(int depth);
}
```
然后,我们定义两个实体类,分别是具体对象 Clothing 和专卖店 Store,它们都继承自 Component,代码如下:
```
public class Clothing extends Component {
public Clothing(String name) {
super(name);
}
public void add(Component component) {
System.out.println("Cannot add to a Clothing");
}
public void remove(Component component) {
System.out.println("Cannot remove from a Clothing");
}
public void display(int depth) {
System.out.println("-".repeat(depth) + name);
}
}
public class Store extends Component {
private List<Component> children = new ArrayList<>();
public Store(String name) {
super(name);
}
public void add(Component component) {
children.add(component);
}
public void remove(Component component) {
children.remove(component);
}
public void display(int depth) {
System.out.println("-".repeat(depth) + name);
for (Component child : children) {
child.display(depth + 2);
}
}
}
```
在 Store 类中,我们定义了一个 children 列表表示其下包含的子元素,可以添加或删除子元素。对于 Clothing 类,由于它是最小的单个对象,所以没有子元素,因此 add() 和 remove() 方法都不需要实现。
最后,在客户端调用时,我们可以按如下方式组装各个元素的关系:
```
public static void main(String[] args) {
Component mall = new Store("The Mall");
Component menClothing = new Store("Men's Clothing");
menClothing.add(new Clothing("Suit"));
menClothing.add(new Clothing("Shirt"));
menClothing.add(new Clothing("Trousers"));
Component womenClothing = new Store("Women's Clothing");
womenClothing.add(new Clothing("Dress"));
womenClothing.add(new Clothing("Blouse"));
womenClothing.add(new Clothing("Skirt"));
Component shoeStore = new Store("Shoe Store");
shoeStore.add(new Clothing("Sneakers"));
shoeStore.add(new Clothing("Formal shoes"));
shoeStore.add(new Clothing("High heels"));
mall.add(menClothing);
mall.add(womenClothing);
mall.add(shoeStore);
mall.display(0);
}
```
输出结果为:
```
The Mall
--Men's Clothing
----Suit
----Shirt
----Trousers
--Women's Clothing
----Dress
----Blouse
----Skirt
--Shoe Store
----Sneakers
----Formal shoes
----High heels
```
这就是一个简单的组合模式实现。希望能帮到您!
阅读全文