public interface Apple {
public String getName();
}
public interface Grape {
public String getName();
}
public class SourApple implements Apple {
public String getName() {
return "Sour Apple! :$";
}
}
public class SourGrape implements Grape {
public String getName() {
return "Sour Grape! :$";
}
}
public class JucyApple implements Apple {
public String getName() {
return "Jucy Apple!";
}
}
public class JucyGrape implements Grape {
public String getName() {
return "Jucy Grape!";
}
}
// interfejs abstrakcyjnej fabryki tworzącej obiekty implementujące interfejsy Apple oraz Grape
public interface FruitFactory {
public Apple createApple();
public Grape createGrape();
}
// implementacja abstrakcyjnej fabryki FruitFactory tworząca obiekty
// konkretnych klas: JucyApple oraz JucyGrape.
public class JucyFruitFactory implements FruitFactory {
// metoda fabrykująca tworząca obiekt klasy JucyApple implementujący interfejs Apple
public Apple createApple() {
return new JucyApple();
}
// metoda fabrykująca tworząca obiekt klasy GrapeApple implementujący interfejs Grape
public Grape createGrape() {
return new JucyGrape();
}
}
// implementacja abstrakcyjnej fabryki FruitFactory tworząca obiekty
// konkretnych klas: SourApple oraz SourGrape.
public class SourFruitFactory implements FruitFactory {
public Apple createApple() {
return new SourApple();
}
public Grape createGrape() {
return new SourGrape();
}
}
// Klasa zawierająca statyczną metodę do pobierania obiektu implementującego
// abstrakcyjną fabrykę FruitFactory. Wybór implementacji fabryki jest uzależniony
// od aktualnego miesiąca.
public class FactoryGetter {
public static FruitFactory getFruitFactory() {
Calendar calendar = Calendar.getInstance();
int month = calendar.get(Calendar.MONTH);
if ((month > Calendar.APRIL) && (month < Calendar.OCTOBER)) {
return new JucyFruitFactory();
} else {
return new SourFruitFactory();
}
}
}
// Przykład zastosowania abstrakcyjnej fabryki
public class Main {
public static void main(String[] arg) {
FruitFactory ff = FactoryGetter.getFruitFactory();
Apple apple = ff.createApple();
System.out.println(apple.getName());
Grape grape = ff.createGrape();
System.out.println(grape.getName());
}
}
Komentarze
Dodaj nowy komentarz