您的位置:首页 > 编程语言 > Java开发

《大话设计模式》java实现之装饰器模式

2017-11-13 10:34 731 查看
Decorator模式个人觉得应该翻译装饰器模式,书中用了装饰模式,个人习惯吧

UML图



代码结构



public class BigTrouser extends Finery {

@Override
public void show() {
super.show();               //书中装饰顺序反过来了,所以这里先写super可以使得顺序的正确
System.out.println("垮裤");
}

}


public class Client {
public static void main(String[] args) {
Person xc = new Person("小菜");
System.out.println("第一种装扮");

BigTrouser kk = new BigTrouser();
Tshirts dtx = new Tshirts();

kk.decorate(xc);
dtx.decorate(kk);  //这两步体现了装饰的过程,与书中不使用模式的代码对比
dtx.show();
}

}


public class Finery extends Person {
private Person component;

@Override
public void show() {
if(component != null) {
component.show();
}
}

public void decorate(Person component) {
this.component = component;
}
}


public class Person {
private String name;

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}

public Person(String name) {
super();
this.name = name;
}

public Person() {
super();
}

public void show() {
System.out.println("装扮的" + name);
}
}


public class Tshirts extends Finery {

@Override
public void show() {
super.show();                //书中装饰顺序反过来了,所以这里先写super可以使得顺序的正确
System.out.println("大T恤");
}

}


注:注释中先写了super,书中在最后写super,主要是顺序的问题

其实java中有一个经典的装饰器模式,就是IO流,换一种实现方法就可以体现了,改后的代码如下:

public class BigTrouser extends Finery {

public BigTrouser(Person person) {
super(person);
}

@Override
public void show() {
super.show();
System.out.println("垮裤");
}

}


public class Client {
public static void main(String[] args) {
Person person = new Person("小菜");

Finery finery = new TShirts(new BigTrouser(person));  //初始化时一层包一层,典型的java流的写法
finery.show();
}
}


public abstract class Finery extends Person {
private Person person;

public Finery(Person person) {
this.person = person;
}

@Override
public void show() {
person.show();
}

}


public class Person {
private String name;

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}

public Person(String name) {
super();
this.name = name;
}

public Person() {
super();
}

public void show() {
System.out.println("装扮的" + name);
}
}


public class TShirts extends Finery {

public TShirts(Person person) {
super(person);
}

@Override
public void show() {
super.show();
System.out.println("T恤");
}

}


主要关注Client中初始化的写法,new xxx(new xxx)这种写法就与java的IO流的写法一致。

装饰器模式主要是可以体现装饰的过程,就像前面中写的http://blog.csdn.net/linlinxie/article/details/78455946
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: