Разбираюсь с абстрактными классами в java и в качестве примера их использования приводиться фабричный метод, и говориться что в данном случае мы можем не создавать именованный экземпляр класса что собственно делает синтаксис более осмысленным, вот пример кода:
interface Service{
void method1();
void method2();
}
interface ServiceFactory{
Service getService();
}
class Implementation1 implements Service{
private Implementation1(){
}
public void method1(){
System.out.println("Implementetion1 print method1");
}
public void method2(){
System.out.println("Implementetion1 print method2");
}
public static ServiceFactory factory =
new ServiceFactory(){
public Service getService(){
return new Implementation1();
}
};
}
class Implementation2 implements Service{
private Implementation2(){
}
public void method1(){
System.out.println("Implementetion2 print method1");
}
public void method2(){
System.out.println("Implementetion2 print method2");
}
public static ServiceFactory factory =
new ServiceFactory() {
@Override
public Service getService() {
return new Implementation2();
}
};
}
class Factories{
public static void serviceConsumer(ServiceFactory fact){
Service s = fact.getService();
s.method1();
s.method2();
}
}
public class AbstractClass {
public static void main(String[] arg){
Factories.serviceConsumer(Implementation1.factory);
Factories.serviceConsumer(Implementation2.factory);
}
}
Не понятно, чем это лучше на практике чем следующий код:
interface Service{
void method1();
void method2();
}
class Implementation1 implements Service{
public void method1(){
System.out.println("Implementetion1 print method1");
}
public void method2(){
System.out.println("Implementetion1 print method2");
}
}
class Implementation2 implements Service{
public void method1(){
System.out.println("Implementetion2 print method1");
}
public void method2(){
System.out.println("Implementetion2 print method2");
}
}
class Factories{
public static void serviceConsumer(Service s){
s.method1();
s.method2();
}
}
public class AbstractClass {
public static void main(String[] arg){
Factories.serviceConsumer(new Implementation1());
Factories.serviceConsumer(new Implementation2());
}
}
В первом случае в Factories.serviceConsumer мы передает конкретное поле конкретного класса, почему бы не передавать сразу объект как во втором случае, к тому же во втором случае кода нужно писать меньше.