允许向一个现有的对象添加新的功能,但是不改变其结构。也就是给一个对象做一个在外的包装。
装饰者模式的创建思路:
1.定义一个接口,该接口中的方法是必须要实现的方法;
2.设计一个或者多个的装饰者,每个都继承接口,并且将接口作为构造函数的参数传入;
3.使用一个主体类,继承接口并且实现确切的功能;
package decorator;
/*
* 装饰者模式
*/
public abstract class Humburger{
public String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public abstract Integer getPrice();
}
package decorator;
/*
* 装饰者模式
*/
public class Chicken extends Humburger{
public Chicken(){
name = "鸡腿堡";
}
@Override
public Integer getPrice() {
// TODO Auto-generated method stub
return 10;
}
}
package decorator;
/*
* 装饰者模式
*/
public class Beef extends Humburger{
public Beef(){
name = "牛肉堡";
}
@Override
public Integer getPrice() {
// TODO Auto-generated method stub
return 15;
}
}
package decorator;
/*
* 装饰者模式
*/
public abstract class Condiment extends Humburger{
public abstract String getName();
}
package decorator;
/*
* 装饰者模式
*/
public class Lettuce extends Condiment{
Humburger humburger;
public Lettuce(Humburger humburger){
this.humburger = humburger;
}
@Override
public String getName() {
// TODO Auto-generated method stub
return humburger.getName()+"生菜";
}
@Override
public Integer getPrice() {
// TODO Auto-generated method stub
return humburger.getPrice()+2;
}
}
package decorator;
/*
* 装饰者模式
*/
public class Chilli extends Condiment{
Humburger humburger;
public Chilli(Humburger humburger){
this.humburger = humburger;
}
@Override
public String getName() {
// TODO Auto-generated method stub
return humburger.getName()+"辣椒";
}
@Override
public Integer getPrice() {
// TODO Auto-generated method stub
return humburger.getPrice();
}
}
package decorator;
/*
* 装饰者模式
*/
public class CreatHum {
public static void main(String[] args) {
Humburger humburger = new Chicken();
System.out.println(humburger.getName()+" 价钱"+humburger.getPrice());
Lettuce lettuce = new Lettuce(new Beef());
System.out.println(lettuce.getName()+" 价钱"+lettuce.getPrice());
Chilli chilli = new Chilli(new Lettuce(new Beef()));
System.out.println(chilli.getName()+" 价钱"+chilli.getPrice());
Chilli chilli1 = new Chilli(new Lettuce(new Chicken()));
System.out.println(chilli1.getName()+" 价钱"+chilli1.getPrice());
}
}
请关注“知了堂学习社区”,地址:http://www.zhiliaotang.com/portal.php