View RSS Feed

fatabass

Decorator Pattern Example

Rating: 2 votes, 2.00 average.
by , 03-03-2012 at 10:27 PM (1428 Views)
Java Code:
package decoratorPattern;

public abstract class Beverage {
	
	String description;
	int size;
	
	public Beverage(int size) {
		this.size = size;
	}
		
	public String getDescription() {
		
		String mySize = null;
		
		if(size == 1)
			mySize = "Small";
		else if(size==2)
			mySize="Medium";
		else if(size==3)
			mySize="Large";
		
		return mySize+ " " + description;
	}
	
	public int getSize() {
		return size;
	}
	
	public abstract double cost();

}


package decoratorPattern;

public abstract class Decorator extends Beverage {
	
	public Beverage beverage;

	public Decorator(int size) {
		super(size);
	}

	
	@Override
	public abstract String getDescription();

}


package decoratorPattern;

public class Mocha extends Decorator {

	public Mocha(Beverage beverage) {
		super(beverage.size);
		this.beverage = beverage;
	}
	
	@Override
	public String getDescription() {
		return beverage.getDescription() + ", Mocha";
	}

	@Override
	public double cost() {
		
		if(beverage.size==1)
		return 0.20 + beverage.cost();
		
		else if(beverage.size==2)
		return 0.40 + beverage.cost();
		
		return 0.60 + beverage.cost();
	}

}


package decoratorPattern;

public class Espresso extends Beverage {
	
	public Espresso(int tsize) {
		super(tsize);
		description = "Espresso";
	}

	@Override
	public double cost() {
		return 1;
	}
}


package decoratorPattern;

public class TestClass 
{

	public static void main(String[] args)
	{
		Beverage myEspresso = new Mocha(new Mocha(new Espresso(1)));

		System.out.println(myEspresso.getDescription());
		System.out.println(myEspresso.cost());
	}
}

Submit "Decorator Pattern Example" to Facebook Submit "Decorator Pattern Example" to Digg Submit "Decorator Pattern Example" to del.icio.us Submit "Decorator Pattern Example" to StumbleUpon Submit "Decorator Pattern Example" to Google

Tags: None Add / Edit Tags
Categories
Uncategorized

Comments

  1. fatabass's Avatar
    • |
    • permalink
    Small Espresso, Mocha, Mocha
    1.4