一、 问题描述
- 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("系上领带");
}
}