处理流
引入1_模拟方法器对人的声音的放大
package com.sxt.IO_01;
public class Decorate {
/**
*@描述:
* @param args
*/
public static void main(String[] args) {
Person p = new Person();
p.say();
Amplify amplify = new Amplify(p);
amplify.say();
}
}
/**
*
* @描述:定义接口
*/
interface Say{
void say();
}
/**
*
* @描述:定义人并实现承接口
*/
class Person implements Say{
int voice = 10;
@Override
public void say() {
System.out.println("原来声音大小为:"+this.voice);
}
}
/**
*
* @描述:定义放大器并继承接口对声音进行放大
*/
class Amplify implements Say{
private Person p;
public Amplify(Person p) {
this.p = p;
}
@Override
public void say() {
System.out.println("放大后的声音为:"+p.voice * 1000);
}
}
引入2_模拟咖啡加料
package com.sxt.IO_01;
/**
* 1、抽象组件(饮料):需要装饰的抽象对象(是接口或抽象父类)
* 2、具体组件(咖啡):需要装饰的对象
* 3、抽象装饰类:包含了对抽象组件的引用以及装饰类所共有的方法
* 4、具体装饰类:被装饰的对象
* @描述:模拟咖啡
*/
public class Decorate_Coffe {
public static void main(String[] args) {
Drink coffee = new Coffee();
System.out.println("价格:"+coffee.cost());
System.out.println("信息:"+coffee.info());
Drink milk = new Milk(coffee);
System.out.println("---------------");
System.out.println("价格:"+milk.cost());
System.out.println("信息:"+milk.info());
System.out.println("------------------");
Drink suger = new Suger(coffee);
System.out.println("---------------");
System.out.println("价格:"+suger.cost());
System.out.println("信息:"+suger.info());
}
}
//1、抽象组件
interface Drink{
//费用
double cost();
//说明
String info();
}
//2、具体组件
class Coffee implements Drink{
double price = 1;
String name ="原味咖啡";
@Override
public double cost() {
return price;
}
@Override
public String info() {
return name;
}
}
//3、抽象装饰类
abstract class Decorate implements Drink{
//对抽象组件的引用
Drink drink;
protected Decorate(Drink drink) {
this.drink = drink;
}
@Override
public double cost() {
return this.drink.cost();
}
@Override
public String info() {
return this.drink.info();
}
}
//4、具体装饰类
//4_1装饰类1
class Milk extends Decorate{
Milk(Drink drink) {
super(drink);
}
@Override
public double cost() {
return super.cost()*4;
}
@Override
public String info() {
return super.info()+"加入了牛奶";
}
}
//4_2、装饰类2
class Suger extends Decorate{
Suger(Drink drink) {
super(drink);
}
@Override
public double cost() {
return super.cost()*2;
}
@Override
public String info() {
return super.info()+"加入了糖";
}
}