打开APP
userphoto
未登录

开通VIP,畅享免费电子书等14项超值服

开通VIP
14. 装饰模式
一. 概念
Decorator(装饰模式):动态地给一个对象添加一些额外的职责。就扩展功能而言, 它比生成子类方式更为灵活。

二. 角色
抽象构件(Component)角色:给出一个抽象接口,以规范准备接收附加责任的对象。
具体构件(ConcreteComponent)角色:定义一个将要接收附加责任的类。
装饰(Decorator)角色:持有一个构件(Component)角色对象的实例,并定义一个与抽象构件接口一致的接口。
具体装饰(ConcreteDecorator)角色:负责给构件对象贴上附加的责任。

三. 实现
一个人往往有许多身份,比如一个男人,他是一个人,同时也可能是父亲,丈夫,也可能是程序员,这是父亲、丈夫和程序员就是具体装饰角色,人则是抽象构件角色,男人则为具体构件角色。

Test.java
public class Test {
public static void main(String[] args) {
Decorator fatherDecorator = new FatherDecorator();
Decorator husbandDecorator = new HusbandDecorator();
Decorator programmerDecorator = new Programmer();
Human like = new Male();
fatherDecorator.setHuman(like);
husbandDecorator.setHuman(fatherDecorator);
programmerDecorator.setHuman(husbandDecorator);
programmerDecorator.work();
}
}
测试类,定义一个Human,分别给他装饰丈夫,父亲和程序员。

Human.java
public interface Human {
public void work();
}
人类,为抽象构件角色。

Male.java
public class Male implements Human {

@Override
public void work() {
System.out.println("好好活着");
}
}
男人类,继承与人类,是具体构件角色。

Decorator.java
public class Decorator implements Human {
private Human human;

public Human getHuman() {
return human;
}

public Decorator setHuman(Human human) {
this.human = human;
return this;
}
public Decorator(){
}

public Decorator(Human human) {
super();
this.human = human;
}

@Override
public void work() {
this.human.work();
}
}
装饰角色。其中有一个抽象构件的对象。

FatherDecorator.java
public class FatherDecorator extends Decorator {
@Override
public void work(){
System.out.println("保护孩子");
super.getHuman().work();
}
}
父亲装饰类,具体装饰类。

HusbandDecorator.java
public class HusbandDecorator extends Decorator {
@Override
public void work(){
System.out.println("保护妻子");
super.getHuman().work();
}
}
丈夫装饰类,具体装饰类。

Programmer.java
public class Programmer extends Decorator {
@Override
public void work(){
System.out.println("写好程序");
super.getHuman().work();
}
}
程序员类,具体装饰类。


本站仅提供存储服务,所有内容均由用户发布,如发现有害或侵权内容,请点击举报
打开APP,阅读全文并永久保存 查看更多类似文章
猜你喜欢
类似文章
【热】打开小程序,算一算2024你的财运
设计模式笔记 – Decorator 装饰模式 (Design Pattern) 及其在J...
详解JAVA面向对象的设计模式 (七)、装饰模式
设计模式Decorator模式(又称Wrapper模式)
设计模式之装饰模式篇(Decorator)
Java设计模式--装饰者模式
扩展系统功能——装饰模式(二)
更多类似文章 >>
生活服务
热点新闻
分享 收藏 导长图 关注 下载文章
绑定账号成功
后续可登录账号畅享VIP特权!
如果VIP功能使用有故障,
可点击这里联系客服!

联系客服