среда, 28 сентября 2011 г.

Паттерн Адаптер (Пример кода)



/**
 * Adaptee
 */
public class Item {
    
    private double position = 0.0;
    
    /**
     * Конструктор задает начальное положение элемента
     * @param initialPosition
     */
    public Item(double initialPosition) {
        position = initialPosition;
        System.out.printf("Now initial position is %.2f inches\n", initialPosition);
    }
    
    /**
     * Перемещает объект на inches дюймов
     * @param inches расстояние для перемещения в дюймах
     */
    public void move(double inches) {
        position +=inches;
        if (inches > 0) {
            System.out.printf("Move forward to %.2f inches\n", inches);
        } else if (inches < 0) {
            System.out.printf("Move backward to %.2f inches\n", Math.abs(inches));
        } else {
            System.out.println("Not moved");
        }
    }
    
    /**
     * Возвращает текущую позицию элемента
     */
    public double getPosition() {
        System.out.printf("Current position is %.2f inches\n", position);
        return position;
    }
}



/**
 * Adapter
 */
public class ItemAdapter {
    private Item item;
    
    private static final double cmInInches = 2.54;
    
    /**
     * Конструктор принимает начальную позицию элемента в сантиметрах
     */
    public ItemAdapter(double initialPosition) {
        item = new Item(convertCmToInches(initialPosition));
        System.out.printf("Now initial position is %.2f cm\n", initialPosition);
    }
    
    /**
     * @param cm смещение в сантиметрах
     */
    public void move(double cm) {
        item.move(convertCmToInches(cm));
        System.out.printf("Move item to %.2f cm\n", cm);
    }
    
    /**
     * Возврашает текущую позицию в сантиметрах
     */
    public double getPosition() {
        double position = convertInchesToCm(item.getPosition());
        System.out.printf("Current position is %.2f cm\n", position);
        return position;
    }
    
    /**
     * Конвертирует сантиметры в дюймы
     */
    private double convertCmToInches(double cm) {
        return cm/cmInInches;
    }
    
    /**
     * Конвертирует дюймы в сантиметры
     */
    private double convertInchesToCm(double inches) {
        return inches*cmInInches;
    }
}


public class Client {
    public static void main(String[] args) {
        ItemAdapter itemAdapter = new ItemAdapter(100.0);
        itemAdapter.move(55.4);
        itemAdapter.getPosition();
        itemAdapter.move(-232.1);
        itemAdapter.getPosition();
    }
}
/**
 * Output:
 * Now initial position is 39,37 inches
 * Now initial position is 100,00 cm
 * Move forward to 21,81 inches
 * Move item to 55,40 cm
 * Current position is 61,18 inches
 * Current position is 155,40 cm
 * Move backward to 91,38 inches
 * Move item to -232,10 cm
 * Current position is -30,20 inches
 * Current position is -76,70 cm
 */