
1、使用说明
(1)装饰者模式可以带来比继承更加灵活的扩展功能,使用更加方法,可以通过组合不同的装饰者对象来获取具有不同行为状态的多样化的结果。装饰者模式比继承更具良好的扩展性,完美的遵循开闭原则,继承是静态的附加责任,装饰者则是动态的附加责任。
(2)装饰类和被装饰类可以独立发展,不会相互耦合,装饰模式是继承的一个替代模式,装饰模式可以动态扩展一个实现类的功能。
2、实例
publicclassHelloWorld{
publicstaticvoidmain(String[]args){
//点一份炒饭
FastFoodfood=newFriedRice();
//花费的价格
System.out.println(food.getDesc()+""+food.cost()+"元");
System.out.println("========");
//点一份加鸡蛋的炒饭
FastFoodfood1=newFriedRice();
food1=newEgg(food1);
//花费的价格
System.out.println(food1.getDesc()+""+food1.cost()+"元");
System.out.println("========");
//点一份加培根的炒面
FastFoodfood2=newFriedNoodles();
food2=newBacon(food2);
//花费的价格
System.out.println(food2.getDesc()+""+food2.cost()+"元");
}
}
//快餐抽象类
abstractclassFastFood{
privatefloatprice;
privateStringdesc;
publicFastFood(){}
publicFastFood(floatprice,Stringdesc){
this.price=price;
this.desc=desc;
}
publicfloatgetPrice(){
returnprice;
}
publicvoidsetPrice(floatprice){
this.price=price;
}
publicStringgetDesc(){
returndesc;
}
publicvoidsetDesc(Stringdesc){
this.desc=desc;
}
//获取价格
publicabstractfloatcost();
}
//炒饭
classFriedRiceextendsFastFood{
publicFriedRice(){
super(10,"炒饭");
}
@Override
publicfloatcost(){
returngetPrice();
}
}
//炒面
classFriedNoodlesextendsFastFood{
publicFriedNoodles(){
super(12,"炒面");
}
@Override
publicfloatcost(){
returngetPrice();
}
}
//配料
abstractclassGarnishextendsFastFood{
privateFastFoodfastFood;
publicFastFoodgetFastFood(){
returnfastFood;
}
publicvoidsetFastFood(FastFoodfastFood){
this.fastFood=fastFood;
}
publicGarnish(FastFoodfastFood,floatprice,Stringdesc){
super(price,desc);
this.fastFood=fastFood;
}
}
//鸡蛋配料
classEggextendsGarnish{
publicEgg(FastFoodfastFood){
super(fastFood,1,"鸡蛋");
}
@Override
publicfloatcost(){
returngetPrice()+getFastFood().getPrice();
}
@Override
publicStringgetDesc(){
returnsuper.getDesc()+getFastFood().getDesc();
}
}
//培根配料
classBaconextendsGarnish{
publicBacon(FastFoodfastFood){
super(fastFood,2,"培根");
}
@Override
publicfloatcost(){
returngetPrice()+getFastFood().getPrice();
}
@Override
publicStringgetDesc(){
returnsuper.getDesc()+getFastFood().getDesc();
}
}原文来自:https://www.py.cn © 版权声明
文章版权归作者所有,未经允许请勿转载。
THE END



















































暂无评论内容