我的github
对于一个Java应用来说,会存在很多的调用关系,比如对象A的方法调用对象B的方法,就说对象A依赖对象B.
常规的做法是在类A中实例化B对象,再进行使用.但是这里存在一个问题,如果将来进行应用升级改进,不再使用B的方法而是使用对象C的方法.如果系统比较大,有多个使用对象B方法的地方就要进行更改,当这个数量达到成百上千个时,修改起来将会非常麻烦.
在工厂模式中,所使用的便是面向对象的多态性,对象是父类,调用的却是子类的方法.
实现原理如图:
1.顶层接口确定方法;
2.子类实现顶层接口;
3. 工厂方法产生实例对象;
4. 向调用者传递对象;
5. 对象设置内部的Top接口变量,并调用方法;
实现代码:
package FactoryMethod;
public class FactoryMethod {
public static void main(String[] args) {
// TODO Auto-generated method stub
TopInterface top = factory.getInstance();
application app = new application(top);
app.AppPrint();
}
}
//应用程序
class application{
private TopInterface Top;//创建内部的顶层接口变量
public application(TopInterface Top) {
this.Top = Top;
}
public void AppPrint() {
Top.Print();
}
}
//建立顶层接口
interface TopInterface{
public void Print();
}
//建立工厂类
class factory{
/*the str can read from the config file*/
private static String str = "outtwo";
//根据不同的值确定实例化不同的对象
public static TopInterface getInstance()
{
if(str.equalsIgnoreCase("outone"))
{
System.out.println("use outone class");
return new outone();
}
else if(str.equalsIgnoreCase("outtwo"))
{
System.out.println("use two class");
return new outtwo();
}
else
{
return null;
}
}
}
//类1
class outone implements TopInterface{
public void Print()
{
System.out.println("this is one out class");
}
}
//类2
class outtwo implements TopInterface{
public void Print()
{
System.out.println("this is two out class");
}
}
当需要更换application中调用的类时,只需修改工厂类中的这个地方即可,该参数也可从配置文件中读取,就不必重新编译程序.
private static String str = "outtwo";
这里有一个问题是,如果按照上面的写法,将会全局修改工厂类中产生的对象.但是有可能有这样的需求,程序中部分使用outone.Print(),部分需修改为outtwo.Print();.因此在设计程序时需要考虑这方面的兼容性.