下面是一个最基础的工厂模式,可是它究竟有什么优势呢?我觉得通过接口 —— 实现类 —— 获得另一个类的对象。这个过程反而我觉得麻烦很多。所以特地向大家请教。
import static MyTools.Print.*;interface Service {
void method1();
void method2();
}interface ServiceFactory {
Service getService();
}class Implementation1 implements Service {
Implementation1() {}
public void method1() {print("Implementation1 method1");}
public void method2() {print("Implementation1 method2");}
} class Implementation1Factory implements ServiceFactory {
public Service getService() {
return new Implementation1();
}
}class Implementation2 implements Service {
Implementation2() {}
public void method1() {print("Implementation2 method1");}
public void method2() {print("Implementation2 method2");}
}class Implementation2Factory implements ServiceFactory {
public Service getService() {
return new Implementation2();
}
} public class Factories {
public static void serviceConsumer(ServiceFactory fact) {
Service s = fact.getService();
s.method1();
s.method2();
}
public static void main(String[] args) {
serviceConsumer(new Implementation1Factory());
serviceConsumer(new Implementation2Factory());
}
}
import static MyTools.Print.*;interface Service {
void method1();
void method2();
}interface ServiceFactory {
Service getService();
}class Implementation1 implements Service {
Implementation1() {}
public void method1() {print("Implementation1 method1");}
public void method2() {print("Implementation1 method2");}
} class Implementation1Factory implements ServiceFactory {
public Service getService() {
return new Implementation1();
}
}class Implementation2 implements Service {
Implementation2() {}
public void method1() {print("Implementation2 method1");}
public void method2() {print("Implementation2 method2");}
}class Implementation2Factory implements ServiceFactory {
public Service getService() {
return new Implementation2();
}
} public class Factories {
public static void serviceConsumer(ServiceFactory fact) {
Service s = fact.getService();
s.method1();
s.method2();
}
public static void main(String[] args) {
serviceConsumer(new Implementation1Factory());
serviceConsumer(new Implementation2Factory());
}
}
解决方案 »
免费领取超大流量手机卡,每月29元包185G流量+100分钟通话, 中国电信官方发货