您的位置:首页 > 其它

装饰模式

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恤、

短裤、

装扮的小明

这里就可以看出,在对象已经实例化了,但是还可以为其添加新的额外的功能,按照顺序不断对一个原来的对象进行装扮。不修改原有的对象结构,但却对原来的对象
添加了额外的功能。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: