IO操作Java(2):装饰设计模式举例

装饰设计模式

1、抽象组件:需要装饰的抽象接口(接口或抽象父类)
2、具体组件:需要装饰的对象
3、抽象装饰类:包含了对抽象组件的引用以及装饰着共有的方法
4、具体装饰类

举例1:模拟声音放大功能

public class DecorateTest1 {
		public static void main(String[] args) {
			Person p = new Person();
			p.say();
			Amplofier am = new Amplofier(p);
			am.say();
		}
}

interface say{
	void say();
}

class Person implements say{
	private int voice=10;
	public int getVoice() {
		return voice;
	}
	public void setVoice(int voice) {
		this.voice = voice;
	}
	public void say() {
		System.out.println("人的声音为:"+this.getVoice());
	}
}


class Amplofier implements say{
	private Person person;
	public void say() {
		
	}
	public Amplofier(Person p) {
		this.person = p;
		System.out.println("人的声音为:"+person.getVoice()*10);
		// TODO 自动生成的构造函数存根
	}
}

举例2:咖啡加糖加奶

public class DecorateCoffee {
	public static void main(String[] args) {
		drink coffee  = new Coffee();
		drink sugar = new Sugar(coffee);//装饰
		System.out.print(sugar.info()+"-->>"+sugar.cost());
		drink milk = new Milk(coffee);//装饰
		System.out.println(milk.info()+"-->"+milk.cost());
		
		milk = new Milk(sugar);//装饰
		System.out.println(milk.info()+"-->"+milk.cost());
	}
}


//抽象组件
interface drink{
	double cost();
	String info();
}

//具体组件
class Coffee implements drink{
	private String name="咖啡";
	
	public double cost() {
		return 10;
	}
	public String info() {
		return name;
	}
}

//抽象装饰类
abstract class Decorate implements drink{
	private drink d;
	public double cost() {
		return this.d.cost();
	}
	
	public String info() {
		return this.d.info();
	}
	
	public Decorate(drink di) {
		// TODO 自动生成的构造函数存根
		this.d = di;
	}
}


//具体装饰类
class Milk extends Decorate{
	public Milk(drink dri) {
		// TODO 自动生成的构造函数存根
		super(dri);
	}
	
	public double cost() {
		return super.cost()*4;
	}
	
	public String info() {
		return super.info()+"加入牛奶";
	}
}


class Sugar extends Decorate{


	public double cost() {
		
		return super.cost()*3;
	}

	public String info() {
		
		return super.info()+"加入了糖";
	}
	
	public Sugar(drink dri) {
		super(dri);
	}
	
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

coder鹏鹏

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值