}
}
public class Factories {
public static void serviceConsumer(ServiceFactory fact) { Service s = fact.getServiceO;
s methodic). s.method2();
}
public static void main(String[] args) {
serviceConsumer(new ImplementationlFactoryO); // Реализации полностью взаимозаменяемы serviceConsumec(new Implementation2FactoryO);
}
} /* Output. Implementation! methodl Implementationl method2 Implementation2 methodl Implementation2 method2 *///:-
Без применения фабрики вам пришлось бы где-то указать точный тип создаваемого объекта Service, чтобы он мог вызвать подходящий конструктор.
Но зачем вводить лишний уровень абстракции? Данный паттерн часто применяется при создании библиотек. Допустим, вы создаете систему для игр, которая позволяла бы играть в шашки и шахматы на одной доске:
//: interfaces/Games.java
// Игровая библиотека с использованием фабрики
import static net.mindview.util.Print.*:
interface Game { boolean moveO; } interface GameFactory { Game getGameO; }
class Checkers implements Game { private int moves = 0: private static final int MOVES = 3: public boolean motfeO {
print("Checkers move " + moves): return ++moves != MOVES;
}
}
class CheckersFactory implements GameFactory {
public Game getGameO { return new CheckersO; }
}
class Chess implements Game { private int moves = 0; private static final int MOVES = 4; public boolean moveO {
print("Chess move " + moves); return ++moves != MOVES;
}
}
class ChessFactory implements GameFactory {
public Game getGameO { return new ChessO; }
}