decoractor装饰模式

来源:互联网 发布:单位换算软件下载 编辑:程序博客网 时间:2024/05/19 12:29

动态的给一个对象添加一些额外的功能




示例代码:

package com.dector;public class Main {public static void main(String[] args) {Beverage b1 =new Soy(new Milk(new HouseBlend()));System.out.println(b1.getDescription()+":"+b1.cost());Beverage b2 = new Soy(new Mocha(new Milk(new HouseBlend())));System.out.println(b2.getDescription()+":"+b2.cost());}}



package com.dector;public abstract class Beverage {String description = "unknow";public String getDescription(){return this.description;}public abstract double cost();}class HouseBlend extends Beverage{public String getDescription(){return "HouseBlend";}@Overridepublic double cost() {// TODO Auto-generated method stubreturn 1.0;}}class DarkRoast extends Beverage{public String getDescription(){return "DarkRoast";}@Overridepublic double cost() {// TODO Auto-generated method stubreturn 2.0;}}abstract class CondimentDecorator extends Beverage{Beverage bev;}class Milk extends CondimentDecorator{private double money = 3.0;public String getDescription(){return "MIlk "+ bev.getDescription();}public Milk(Beverage b){this.bev = b;}@Overridepublic double cost() {// TODO Auto-generated method stubreturn this.money + bev.cost();}}class Mocha extends CondimentDecorator{private double money = 4.0;public String getDescription(){return "Mocha "+ bev.getDescription();}public Mocha(Beverage b){this.bev = b;}@Overridepublic double cost() {// TODO Auto-generated method stubreturn this.money + bev.cost();}}class Soy extends CondimentDecorator{private double money = 5.0;public String getDescription(){return "Soy "+ bev.getDescription();}public Soy(Beverage b){this.bev = b;}@Overridepublic double cost() {// TODO Auto-generated method stubreturn this.money + bev.cost();}}


原创粉丝点击