在这我们需要对工厂方法设计模式尽心一个学习,这对框架的创建是十分有力的。
其实我们学习的接口呢,是实现多重继承的一种途径,而你去生成遵循某个接口的对象的典型方式就是工厂方法设计模式。通过这种方式,我们的代码将完全与接口的实现分离,这是十分有利于我们将某个实现替换为另一个实现。
我们在工厂对象上调用的是创建方法,而该工厂对象的将生成接口的某个实现的对象。
话不多时,直接那代码来看:
package lession08;
interface Service {
void method1();
void method2();
}
interface ServiceFactory{
Service getService();
}
class Implementation1 implements Service{
Implementation1(){}//Package access
public void method1() {
System.out.println("Implementation1 method1");
}
public void method2() {
System.out.println("Implementation1 method2");
}
}
class Implementation1Factory implements ServiceFactory{
public Service getService() {
return new Implementation1();
}
}
class Implementation2 implements Service{
Implementation2(){}
public void method1() {
System.out.println("Implementation2 method1");
}
public void method2() {
Syste