装饰设计模式-java

 

 

package cn.shuishandt.opp;

public class DecorateTest2 {
    public static void main(String[] args) {
    	Coffe coffe = new Coffe();
    	System.out.println(coffe.cost()+"=============>"+coffe.info());
    	Milk milk = new Milk(coffe);
    	System.out.println(milk.cost()+"=============>"+milk.info());
    	Suger suger = new Suger(coffe);
    	System.out.println(suger.cost()+"=============>"+suger.info());
    	
    	Suger suger2 = new Suger(milk);
    	System.out.println(suger2.cost()+"=============>"+suger2.info());
    	
    }
}


// 第一步 实现一个接口  公共接口
interface Drink{
	double cost();
	String info();
}

//第二部   实现一个具体的类
class Coffe implements Drink{
	private String name = "原味卡法";

	@Override
	public double cost() {
		// TODO Auto-generated method stub
		return 10;
	}

	@Override
	public String info() {
		// TODO Auto-generated method stub
		return name;
	}
	
}

//第三步  实现一个抽象类  开始装饰   

abstract class Decorate implements Drink{
	// 增加对抽象组件的引用
	private Drink drink;
	
	public Decorate(Drink drink) {
		this.drink = drink;
	}

	@Override
	public double cost() {
		// TODO Auto-generated method stub
		return this.drink.cost();
	}

	@Override
	public String info() {
		// TODO Auto-generated method stub
		return this.drink.info();
	}
	
}

//第四步 写具体的装饰类  对抽象类的实现

class Milk extends Decorate{

	public Milk(Drink drink) {
		super(drink);
		// TODO Auto-generated constructor stub
	}
	public double cost() {
		// TODO Auto-generated method stub
		return super.cost()*4;
	}

	@Override
	public String info() {
		// TODO Auto-generated method stub
		return super.info()+"加了牛奶";
	}
	
	
}

class Suger extends Decorate{

	public Suger(Drink drink) {
		super(drink);
		// TODO Auto-generated constructor stub
	}
	public double cost() {
		// TODO Auto-generated method stub
		return super.cost()*2;
	}

	@Override
	public String info() {
		// TODO Auto-generated method stub
		return super.info()+"加了蔗糖";
	}
	
}

  

posted @ 2023-04-01 10:27  巨兽~墨菲特  阅读(8)  评论(0编辑  收藏  举报