装饰模式
2017-08-27 13:08
92 查看
装饰模式
装饰模式 动态的给一个对象添加一些额外的职责。比继承添加的方式更加灵活。允许向一个现有的对象添加新的功能,同时又不改变其结构。这种类型的设计模式属于结构型模式,它是作为现有的类的一个包装。
关键代码: 1、Component
类充当抽象角色,不应该具体实现。 2、修饰类引用和继承 Component 类,具体扩展类重写父类方法。
装饰器模式,这里使用装饰器来打扮一个人,(来自大话设计模式)
新建人的类
public class Person {
private String
name;
public Person() {
}
public Person(String
name) {
this.name =
name;
}
public
void show() {
System.out.println("装扮的"+name);
}
}
新建一个装扮的基类服饰类
public class Finery
extends Person{
protected Person
person;
@Override
public
void show() {
if (this.person!=null) {
person.show();
}
}
public
void decorator(Person person) {
this.person =
person;
}
}
针对于各个服饰继承服饰类实现各个服饰
public class LeatherShoes
extends Finery{
@Override
public
void show() {
System.out.println("皮鞋、");
super.show();
}
}
public class Necktie
extends Finery{
@Override
public
void show() {
System.out.println("领带、");
super.show();
}
}
等等。。。
在实例类中,依次装扮上不同的服装
public static
void main(String[]
args) {
Person xiaoming =
new Person("小明");
Finery tshirt =
new TShirts();
Finery jeans =
new Jeans();
Finery leatherShoes =
new LeatherShoes();
jeans.decorator(xiaoming);
tshirt.decorator(jeans);
leatherShoes.decorator(tshirt);
leatherShoes.show();
Finery sneaker =
new Sneaker();
Finery shorts =
new Shorts();
shorts.decorator(xiaoming);
tshirt.decorator(shorts);
sneaker.decorator(tshirt);
sneaker.show();
}
输出结果
皮鞋、
T恤、
牛仔裤、
装扮的小明
运动鞋、
T恤、
短裤、
装扮的小明
这里就可以看出,在对象已经实例化了,但是还可以为其添加新的额外的功能,按照顺序不断对一个原来的对象进行装扮。不修改原有的对象结构,但却对原来的对象
添加了额外的功能。
相关文章推荐
- 设计模式(十)装饰器模式
- IOS设计模式之装饰器模式
- 和空姐一起聊聊装饰模式
- 装饰模式(Decorator)
- 装饰模式
- 着装展示之装饰模式学习笔记[C++版]
- 设计模式笔记之装饰模式---变继承关系为组合关系
- C#设计模式之 :Decorator模式(装饰模式)
- 用装饰模式装饰 Servlet Request 对象
- Design Pattern - 装饰模式
- 设计模式之装饰模式篇(Decorator)
- 装饰模式 (Decoratory)
- 【GOF23设计模式】_装饰模式_IO流底层架构_装饰和桥接模式的区别JAVA240
- java 设计模式 装饰模式
- php 装饰模式
- iOS开发-装饰模式
- 11,装饰模式-孙悟空的六神装
- 设计模式系列(四)——装饰模式
- 设计模式:装饰模式
- java设计模式之装饰模式