一、 问题描述
- QQ秀有给模型小人,穿戴衣服的功能,就像人类穿衣一样。假设衣服的种类有西装、大T恤、垮裤、破球鞋、领带、皮鞋等,你如何给小人着装?顺序如何?请设计并实现一个着装程序。
二、 完成如下题目要求
-
画出静态图

-
写出采用该设计模式的好处
1. 把类中的装饰功能从类中搬移去除,这样可以简化原有的类;
2. 可以有效地把类的核心职责和装饰功能区分开
3. 去除相关类中重复的装饰逻辑
- 编写代码
//主方法
public class Main {
public static void main(String[] args) {
Person person=new Person("小明");
BusinessSuit businessSuit=new BusinessSuit();
Tie tie=new Tie();
LeatherShoes leatherShoes=new LeatherShoes();
businessSuit.Decorate(person);
leatherShoes.Decorate(businessSuit);
tie.Decorate(leatherShoes);
tie.show();
}
}
//原有类的主要行为
public class Person {
private String name;
public Person() {
}
public Person(String name) {
super();
this.name = name;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public void show() {
System.out.println(name+"的装扮:");
}
}
//装饰
public class Clothing extends Person {
private Person component;
public void Decorate(Person component){
this.component = component;
}
@Override
public void show() {
if(this.component!=null) {
component.show();
}
}
}
public class Pants extends Clothing{
@Override
public void show() {
// TODO Auto-generated method stub
super.show();
System.out.println("穿上垮裤");
}
}
public class BigT_Shirt extends Clothing{
@Override
public void show() {
// TODO Auto-generated method stub
super.show();
System.out.println("穿上大T恤");
}
}
public class BusinessSuit extends Clothing{
@Override
public void show() {
// TODO Auto-generated method stub
super.show();
System.out.println("穿上西装");
}
}
public class LeatherShoes extends Clothing{
@Override
public void show() {
// TODO Auto-generated method stub
super.show();
System.out.println("穿上皮鞋");
}
}
public class Sneakers extends Clothing {
@Override
public void show() {
// TODO Auto-generated method stub
super.show();
System.out.println("穿上破球鞋");
}
}
public class Tie extends Clothing{
@Override
public void show() {
super.show();
System.out.println("系上领带");
}
}
这篇博客介绍了如何使用装饰设计模式为QQ秀小人进行着装,包括西装、领带、皮鞋等。通过将装饰功能从Person类中分离,简化了原有类,并允许动态组合不同的装饰,实现了多样化的装扮效果。程序中展示了如何通过BusinessSuit、Tie和LeatherShoes装饰类给Person对象添加不同装扮,并通过show方法展示最终装扮结果。
1244

被折叠的 条评论
为什么被折叠?



