четверг, 20 октября 2011 г.

Паттерн Декоратор (Decorator). Пример кода


public interface Car {
    public int getPrice();
    public String getDescription();
}

public class SimpleCar implements Car {

    @Override
    public int getPrice() {
        return 100000;
    }

    @Override
    public String getDescription() {
        return "Simple auto";
    }
}

public abstract class CarDecorator implements Car {
    
    protected final Car car;
    
    public CarDecorator(Car car) {
        this.car = car;
    }

    @Override
    public int getPrice() {
        return car.getPrice();
    }

    @Override
    public String getDescription() {
        return car.getDescription();
    }
}

public class Conditioner extends CarDecorator {
    public Conditioner(Car car) {
        super(car);
    }
    
    public int getPrice() {
        return car.getPrice() + 2000;
    }
    
    public String getDescription() {
        return car.getDescription() + " with conditioner";
    }
}

public class LeatherInterior extends CarDecorator {
    public LeatherInterior(Car car) {
        super(car);
    }
    
    public int getPrice() {
        return car.getPrice() + 3000;
    }
    
    public String getDescription() {
        return car.getDescription() + " with leather interior";
    }
}

public class Client {
    public static void main(String[] args) {
        Car car = new SimpleCar();
        System.out.println("Price: " + car.getPrice() 
            + ", Description: " + car.getDescription());
        
        car = new Conditioner(car);
        System.out.println("Price: " + car.getPrice() 
            + ", Description: " + car.getDescription());
        
        car = new LeatherInterior(car);
        System.out.println("Price: " + car.getPrice() 
            + ", Description: " + car.getDescription());
    }
}
/**
 * Output:
 * Price: 100000, Description: Simple auto
 * Price: 102000, Description: Simple auto with conditioner
 * Price: 105000, Description: Simple auto with conditioner with leather interior
 */


Комментариев нет:

Отправить комментарий