java设计模式--装饰者模式

照例搬一篇文章链接,我通常会选择带有uml图的 方便理解,我只贴代码,由于我以为别人理解的比我透彻,写的比我好 http://www.cnblogs.com/stonefeng/p/5679638.htmlhtml

装饰者模式能够给对象添加一些额外的东西,设计模式那种书中举例是星巴克的例子,若是每一种作法都写一个类的话大概会爆炸,因此选择灵活的方式设计模式

1.建立抽象类,定义基本的行为,装饰者和被装饰着都去继承他ide

public abstract class Component {this

public String desc = "我是抽象组件,他们的共同父类";

public String getDesc() {
return desc;
}

public abstract int price();

}设计

2.被装饰者htm

public class ACupCoffe extends Component{对象

public ACupCoffe() {
desc = "一杯咖啡";
}
@Override
public int price() {
// TODO Auto-generated method stub
return 10;
}blog

}继承

3.装饰者get

public abstract class Decorator extends Component{

public abstract String getDesc();
}

4.具体装饰者1

public class Coffee extends Decorator{

private Component acupcoffe;

public Coffee(Component acupcoffe) {
this.acupcoffe = acupcoffe;
}
@Override
public String getDesc() {
// TODO Auto-generated method stub
return acupcoffe.getDesc() + "咖啡";
}

@Override
public int price() {
// TODO Auto-generated method stub
return acupcoffe.price() + 10;
}

}

5.具体装饰者2

public class Sugar extends Decorator{

private Component acupcoffe;
public Sugar(Component aCupCoffe) {
this.acupcoffe = aCupCoffe;
}
@Override
public String getDesc() {

return acupcoffe.getDesc() + "糖";
}

@Override
public int price() {
// TODO Auto-generated method stub
return acupcoffe.price() + 10;
}

}

6.客户端

public class Client {

public static void main(String[] args) {
Component aCupCoffe = new ACupCoffe();

aCupCoffe = new Sugar(aCupCoffe);
System.out.println(aCupCoffe.getDesc());
System.out.println(aCupCoffe.price());

aCupCoffe = new Coffee(aCupCoffe);
System.out.println(aCupCoffe.getDesc());
System.out.println(aCupCoffe.price());
}

}

相关文章
相关标签/搜索