IO_装饰器设计模式

目录

装饰器的组成

装饰器简单使用

扩音器代码

咖啡代码


装饰器的组成

1.抽象组件:需要装饰的抽象对象(接口或抽象父类)

2.具体组件:需要装饰的对象(被装饰者)

3.抽象装饰类:包含抽象组件的引用和装饰类共有的方法

4.具体装饰类:用于装饰的类

装饰器简单使用

扩音器代码

package cn.sxt.IO02;
/*
 * 实现扩音器,对人的声音放大
 */
public class Decreat_test01 {

	public static void main(String[] args) {
		Person p =new Person();
		p.say();
		amply a=new amply(p);
		a.say();

	}

}

interface say {//
	void say();
}

class Person implements say{

	private int voice=10;
	public void say() {
    System.out.println("人的声音"+this.voice);
	}
	public int getVoice() {
		return voice;
	}
	//get方法
	public void setVoice(int voice) {
		this.voice = voice;
	}
	
	
}

class amply implements say{
	private Person p;
    public amply(Person p) {
		this.p=p;
	}

	public void say() {
    System.out.println("扩音后"+p.getVoice()*100);
	}
}

咖啡代码

package cn.sxt.IO02;
/*
 * 装饰咖啡
 * 
 * 1.抽象组件:需要装饰的抽象对象(接口或抽象父类)
2.具体组件:需要装饰的对象(被装饰者)
3.抽象装饰类:包含抽象组件的引用和装饰类共有的方法
4.具体装饰类:用于装饰的类
 */
public class Decreat_test02 {
	public static void main(String[] args) {
		Drink coffed=new Coffe();
		Drink milkcoffee=new Milk(coffed);
		Drink sugercoffe =new Suger(milkcoffee);
		System.out.println(coffed.info()+coffed.price());
		System.out.println(milkcoffee.info()+milkcoffee.price());
		System.out.println(sugercoffe.info()+sugercoffe.price());
	}

}
//抽象组件
interface Drink{
	double price();
	String info();
}
//具体组件
class Coffe implements Drink{

	private String name="原味咖啡";
	public double price() {
		return 20;
	}
	public String info() {
		return name;
	}
}
//抽象装饰类
 abstract class Decreat implements Drink{
    
	 private Drink drink;
	 
	public Decreat(Drink drink) {
		super();
		this.drink = drink;
	}

	@Override
	public double price() {
		
		return this.drink.price();
	}

	public String info() {
		return this.drink.info();
	}
	
}
  class Milk extends Decreat{

	public Milk(Drink drink) {
		super(drink);
	} 	
	public double price() {		
		return super.price()*2;
	}
	@Override
	public String info() {
		return super.info()+"加了牛奶";
	}
  }
  class Suger extends Decreat{

		public Suger(Drink drink) {
			super(drink);
		} 	
		public double price() {		
			return super.price()*3;
		}
		@Override
		public String info() {
			return super.info()+"加了唐";
		}
	  }

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值