目录
1. 什么是装饰模式
2.装饰模式(Decorator)结构图
3.代码实现
3.1 装扮代码结构图
3.2 具体代码实现
3.3 运行结果
4.回顾总结
1. 什么是装饰模式动态地给一个对象添加一些额外的职责,就添加功能来说,装饰模式比生成子类更为灵活。
2.装饰模式(Decorator)结构图 3.代码实现 3.1 装扮代码结构图 3.2 具体代码实现public class Person {
private String name;
public Person() {
}
public Person(String name) {
this.name = name;
}
public void show() {
System.out.println("装扮的"+ this.name);
}
}
public class Finery extends Person {
protected Person component;
public void decorate(Person component) {
this.component = component;
}
@Override
public void show() {
if (component != null) {
component.show();
}
}
}
public class BigTrouser extends Finery{
@Override
public void show() {
System.out.println("跨库 ");
super.show();
}
}
public class LeatherShoes extends Finery {
@Override
public void show() {
System.out.println("皮鞋 ");
super.show();
}
}
public class Sneakers extends Finery{
@Override
public void show() {
System.out.println("破球鞋 ");
super.show();
}
}
public class Suit extends Finery {
@Override
public void show() {
System.out.println("西装 ");
super.show();
}
}
public class Tie extends Finery{
@Override
public void show() {
System.out.println("领带 ");
super.show();
}
}
public class TShirts extends Finery{
@Override
public void show() {
System.out.println("大T恤 ");
super.show();
}
}
public class Main {
public static void main(String[] args) {
Person xc = new Person();
System.out.println("第一种装扮");
Sneakers pqx = new Sneakers();
BigTrouser kk = new BigTrouser();
TShirts dtx = new TShirts();
pqx.decorate(xc);
kk.decorate(pqx);
dtx.decorate(kk);
dtx.show();
System.out.println("第二种装扮");
LeatherShoes px = new LeatherShoes();
Tie ld = new Tie();
Suit xz = new Suit();
px.decorate(xc);
ld.decorate(px);
xz.decorate(ld);
xz.show();
}
}
3.3 运行结果 4.回顾总结优点:把类中的装饰功能从类中版已去除,这样可以简化原有的类,这样可以有效的把类的核心职责和装饰功能分开了,而且可以去除相关类中重复的装饰逻辑。