public abstract class Animal {
AnimalImp animalImp;
public Animal(AnimalImp animalImp) {
this.animalImp = animalImp;
}
public void say() {
animalImp.say();
}
}
public class HappyAnimal extends Animal {
public HappyAnimal(AnimalImp animalImp) {
super(animalImp);
}
}
public interface AnimalImp {
public void say();
}
public class Cat implements AnimalImp {
public void say() {
System.out.println("Miaou! I'm a happy cat!");
}
}
public class Pig implements AnimalImp {
public void say() {
System.out.println("Groin-groin! I'm a happy pig!");
}
}
public class Rooster implements AnimalImp {
public void say() {
System.out.println("Cocorico! I'm a happy rooster!");
}
}
import java.util.ArrayList;
import java.util.List;
public class Client {
public static void main(String[] args) {
List happyAnimals = new ArrayList();
happyAnimals.add(new HappyAnimal(new Cat()));
happyAnimals.add(new HappyAnimal(new Pig()));
happyAnimals.add(new HappyAnimal(new Rooster()));
for (Animal animal: happyAnimals) {
animal.say();
}
}
}
/**
* Output:
* Miaou! I'm a happy cat!
* Groin-groin! I'm a happy pig!
* Cocorico! I'm a happy rooster!
*/
среда, 5 октября 2011 г.
Паттерн Мост (Bridge). Пример кода
Подписаться на:
Комментарии к сообщению (Atom)
Комментариев нет:
Отправить комментарий