您的位置:首页 > 其它

装饰模式例子(Decorator Pattern)

2016-12-01 22:31 344 查看
/*
* 人类
*/
public class Person {

public Person() {
}

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

private String name;

public String getName() {
return name;
}

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

public void show(){
System.out.println("来自Person");
}
}


/*
* 服饰类
*/
public class Decorator extends Person {
protected Person person;

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

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


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


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


/*
* 客户端
*/
public class App {
public static void main(String[] args) {
Person p1 = new Person("小菜");

TShirts ts = new TShirts();
BigTrouser bt = new BigTrouser();

ts.Decorate(p1);
bt.Decorate(ts);

bt.show();

}
}


内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息