decoractor装饰模式

本文介绍了一种使用Java实现的装饰者模式案例,该模式允许在不改变原有对象的前提下为其添加新的功能。通过具体示例展示了如何为饮料添加不同的配料,并计算最终价格。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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




示例代码:

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";
	}
	@Override
	public double cost() {
		// TODO Auto-generated method stub
		return 1.0;
	}
}

class DarkRoast extends Beverage{
	public String getDescription()
	{
		return "DarkRoast";
	}
	@Override
	public double cost() {
		// TODO Auto-generated method stub
		return 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;
	}
	@Override
	public double cost() {
		// TODO Auto-generated method stub
		return 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;
	}
	@Override
	public double cost() {
		// TODO Auto-generated method stub
		return 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;
	}
	@Override
	public double cost() {
		// TODO Auto-generated method stub
		return this.money + bev.cost();
	}
}





















评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值